Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Arrange a list in multiple rows and columns

Tags:

html

css

flexbox

I have an simple ordered list inside my template file, which I can't change.

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

Is there a way to order my content like so: two columns, the last item will always be on the second column.

I tried flex, but I couldn't find a way to break the flow after the third item. Is there a way to do this via CSS or will I have to resort to hacking it with jQuery?

like image 336
Norbert Avatar asked Mar 19 '16 15:03

Norbert


People also ask

How do I display a list in two rows?

You need to set the width of UL, because number of rows will depend on the width also even after setting the column-count. You can set it to 100% too, but then the number of rows will change based on the window size. To restrict the number of rows to 2, fixed width for UL may be required.

How do you do ul li in two columns?

This is the simplest way to do it. CSS only. add width to the ul element. add display:inline-block and width of the new column (should be less than half of the ul width).

Is there a way to break a list into columns?

If you want a preset number of columns, you can use column-count and column-gap, as mentioned above. However, if you want a single column with limited height that would break into more columns if needed, this can be achieved quite simply by changing display to flex.


1 Answers

You can do this with Flexbox using flex-direction: column and flex-wrap: wrap, here is Fiddle

Update: This is not great solution because you have to use fixed height on parent element also if your content overflows one of li it will break layout as you can see here Fiddle but it could be useful in some cases.

body, html {
  margin: 0;
  padding: 0;
}

* {
  box-sizing: border-box;
}

ul {
  height: 100vh;
  padding: 0;
  margin: 0;
  list-style-type: none;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

li {
  width: 50%;
}

li:nth-child(1) {
  background: #000000;
  flex: 0 0 33.33%;
}

li:nth-child(2) {
  background: #30BB75;
  flex: 0 0 33.33%;
}

li:nth-child(3) {
  background: #BB3047;
  flex: 0 0 33.33%;
}

li:nth-child(4) {
  flex: 0 0 100%;
  background: #305EBB;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>
like image 101
Nenad Vracar Avatar answered Nov 14 '22 19:11

Nenad Vracar