0

Is it possible to split a list into 2 columns if the number of child <li> exceeds 5, for example, in pure CSS?

In my example, I want the following to happen:

  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>

if the number of <li> elements exceeds 5, I want it to appear like this:

  <li>1</li>    <li>6</li>
  <li>2</li>    <li>7</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
Heretic Monkey
  • 10,498
  • 6
  • 45
  • 102
Dave
  • 1,177
  • 2
  • 16
  • 44
  • 2
    Does this answer your question? [Is there a way to break a list into columns?](https://stackoverflow.com/questions/6509106/is-there-a-way-to-break-a-list-into-columns) – Ben Sewards Mar 03 '20 at 15:17

1 Answers1

2

If you are able to use CSS grid you can do this with grid-template and grid-auto-flow directive:

.list {
  display: grid;
  grid-template-rows: repeat(5, min-content);
  grid-auto-flow: column;
}
<ul class="list">
  <li class="item">1</li>
  <li class="item">2</li>
  <li class="item">3</li>
  <li class="item">4</li>
  <li class="item">5</li>
  <li class="item">6</li>
  <li class="item">7</li>
</ul>
Hunter McMillen
  • 52,839
  • 21
  • 105
  • 154
  • Note that the template column declaration is unnecessary as the grid will create a new column automagically every 5 items. - https://codepen.io/Paulie-D/pen/zYGdEQq – Paulie_D Mar 03 '20 at 15:20
  • Please add your answer to the duplicate question. – Heretic Monkey Mar 03 '20 at 15:20
  • @HereticMonkey I don't think this is a duplicate of that question. Break a list into columns versus start a new columns after X items are not the same thing. – Hunter McMillen Mar 03 '20 at 15:23
  • @Paulie_D oh cool, I wasn't aware it worked like that with `min-content`. I'll update since that more accurately reflects that they likely want. Unless you want to post an answer? – Hunter McMillen Mar 03 '20 at 15:24
  • Certainly there are other duplicates that are more appropriate then? This is a common question... [CSS/html display list in two columns if more than X amount of elements?](https://stackoverflow.com/q/33217009/215552) perhaps? – Heretic Monkey Mar 03 '20 at 15:26
  • wow, this is amazing! @Paulie_D, your codepen was extremely helpful as well. thanks! – Dave Mar 03 '20 at 15:42
  • 1
    @HereticMonkey copied this answer over to the duplicate you mentioned. – Hunter McMillen Mar 04 '20 at 14:05