How to set 2 flex items on row and the last item in a row expand full width?

Issue

I need a css flex way to set 2 items per row and in each row the second item to expand with width auto.

I tried a lot of things, like setting margin-right:auto for second item in each row, but is not working.

Here is what I have now:

div{
  display:flex;
  flex-wrap:wrap;
}
div span{
  background:red;
  margin:2px;
  white-space:nowrap;
}
div span:nth-child(2),
div span:nth-child(4),
div span:nth-child(6){
  flex-basis:100%;
  background:yellow;
}
<div>
  <span>aaa</span>
  <span>bbbbbb</span>
  <span>ccccccccc</span>
  <span>ddd</span>
  <span>eee</span>
  <span>fff</span>
</div>

The text inside a flex item should not wrap.

Here is the result I need:

enter image description here

Solution

This layout can’t work with Flex, because each row is independent from other rows, and column widths cannot be defined.

However, the solution is simple with Grid, because column widths can be defined.

 div {
   display: grid;
   grid-template-columns: min-content 1fr;
 }

 div span {
   background: red;
 }

 div span:nth-child(2),
 div span:nth-child(4),
 div span:nth-child(6) {
   background: yellow;
 }
<div>
  <span>aaa</span>
  <span>bbbbbb </span>
  <span>ccccccccc</span>
  <span>ddd</span>
  <span>eee</span>
  <span>fff</span>
</div>

In the code above, grid-template-columns defines two columns.

The first is set to width min-content, which means it will size to the minimum width possible.

The second is set to 1fr, which means it will take all remaining space.

Answered By – Michael Benjamin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published