daveycroqet daveycroqet - 1 month ago 7
HTML Question

Flexbox: Place last two items in a row, inside a single column

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?

https://jsfiddle.net/511qb3py/

HTML:



<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>


CSS:



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;
}

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. Subsequent items are forced to new lines.
  • Give the last two item (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%;
  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>

Comments