daveycroqet daveycroqet - 1 month ago 5
CSS Question

In a column of flex items, place the last two items in a single row

Without modifying the HTML or using some

position: absolute
hackery, is it possible to make items 6 and 7 in this list appear side-by-side on row 6?



ul {
border: 1px solid gray;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
list-style-type: none;
}
li {
width: 33%;
border: 1px solid #ccc;
text-align: center;
}

<div class="flex-container">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
</div>





https://jsfiddle.net/511qb3py/

Answer

Here's one method:

  • Switch the flex-direction to row.
  • Enable wrap.
  • Give each flex item enough width so that only one can fit on a line. This forces the following items to create new lines.
  • Give the last two items (6 and 7) a width that enables both to fit on one line.

ul {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  list-style-type: none;
  border: 1px solid gray;
}
li {
  flex: 0 0 66%; /* flex-grow flex-shrink flex-basis */
  text-align: center;
  border: 1px solid #ccc;
}
li:nth-last-child(-n + 2) {
  flex-basis: 45%;
}
<div class="flex-container">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
    <li>7</li>
  </ul>
</div>