0

I have a simple flexbox set up where items have a fixed width and nicely wrap to the next row when needed:

enter image description here

However, when the parent element width is small enough and elements appear all in a single column, the whitespace to the right of the elements can look quite awkward:

enter image description here

Is there a simple way to keep the behavior in the first screenshot, but have elements fill the full width of the parent element when in a single "column"? I can't use media queries as far as I know because I need things to be relative to a specific parent element and not the whole screen width. Things would look like this ideally in the one column case:

enter image description here

Sample code below:

.cont {
  display: flex;
  flex-wrap: wrap;
  overflow: auto;
}

.item {
  flex: 0 1 auto;
  width: 200px;
  height: 50px;
  border: 1px solid black;
  background: red;
  margin-right: 10px;
  margin-bottom: 10px;
}
<div class="cont">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>
JKillian
  • 18,061
  • 8
  • 41
  • 74

1 Answers1

1

Add this style in media query

@media screen and (max-width: 480px) {
  .item {
    width: 100%;
  }
}

.cont {
  display: flex;
  flex-wrap: wrap;
  overflow: auto;
}

.item {
  flex: 0 1 auto;
  width: 200px;
  height: 50px;
  border: 1px solid black;
  background: red;
  margin-right: 10px;
  margin-bottom: 10px;
}

@media screen and (max-width: 480px) {
  .item {
    width: 100%;
  }
}
<div class="cont">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>
Nandita Sharma
  • 13,287
  • 2
  • 22
  • 35
  • Keep max-width's value the one at which all divs stack above each other. – Nandita Sharma Jun 19 '18 at 15:53
  • Unfortunately, I can't rely on media queries because my elements are children of a div that can change in size depending on a user set layout. I updated my question to reflect that info – JKillian Jun 19 '18 at 15:53
  • there is no way of knowing for sure when they will all stack :( Please post the complete ques so that we can try helping you :) – Nandita Sharma Jun 19 '18 at 15:56