Flexbox: fill remaining space but wrap up anyway

Is it possible to tell flexbox items to fill the remaining space, but wrap as soon as they become smaller than their content.

Some elements have a fixed percentage width.

Html

<div class="grid">
  <div class="grid__item">column auto</div>
  <div class="grid__item one-third">column 33.333%</div>
  <div class="grid__item one-third">column 33.333%</div>
  <div class="grid__item">column auto</div>      
</div>

      

CSS

.grid {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  background: gray;
}

.grid__item {
  background: red;
  flex: 1;
}

.one-third {
  flex-basis: 33.333%;
  background: green;
}

      

I want fixed width (green) elements to always have 33.333% width. The rest of the items (red) should fill the remaining space. If the screen gets smaller, I want the elements to wrap if there isn't enough room for their content.

I thought I could just use flex: 1

and flex-wrap: wrap

in the container to do something like this, but as you can see in the pen it doesn't wrap at all. If I remove flex: 1

in .grid__item

, they look like a sort of wrapper, but not all down to very small screen sizes.

+3


source to share


2 answers


You can of course allow the wrapping, but I'm not entirely sure the effect is what you want. If you have an image of how you expect it to look after wrapping, we can improve there.

Demo Codepen



* {
  box-sizing: border-box;
}
.grid {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  background: gray;
}
.grid__item {
  background: red;
  flex: 1 0 auto;
  padding: 1em;
}
.one-third {
  flex: 0 0 33.333%;
  background: green;
  border: 1px solid lightgreen;
}
      

<div class="grid">
  <div class="grid__item">Lorem ipsum dolor sit amet</div>
  <div class="grid__item one-third">column 33.333%</div>
  <div class="grid__item one-third">column 33.333%</div>
  <div class="grid__item">Lorem ipsum dolor sit amet,</div>
</div>
      

Run codeHide result


+6


source


flex:1

it will shrink infinitely because it means flex-grow:1 ;flex-shrink:1

try to install flex: 1 0 auto;



Pen

+2


source







All Articles