CSS: sort list in multiple rows and columns

I have a simple ordered list inside my template file that I cannot change.

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

Is there a way to arrange my content as follows: two columns, the last element will always be in the second column.

corBwum.png

I tried flex, but could not find a way to break the stream after the third element. Is there a way to do this using CSS, or will I have to resort to hacking it using jQuery?

+5
source share
3 answers

I worked this out for hours and did not find a suitable solution that did not imply a fixed height on the container. The closest I found is to use the column-count property and add a column splitting to the last element, which now only works in Chrome:

 ul { -webkit-column-count: 2; column-count: 2; } li:last-of-type { -webkit-column-break-before: always; } 

Jsfiddle

0
source

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

Update: This is a great solution because you have to use a fixed height in the parent element, also if your content overflows with one of li , it will break the layout, since you can see Fiddle , but it can 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> 
+4
source

Based on the answer of Nenad Vracar, you can do the same with a dynamic number of elements without resorting to absolute percentages using flex-grow . Example:

 ul { height: 200px; /* Whatever */ list-style-type: none; display: flex; flex-direction: column; flex-wrap: wrap; } li { width: 50%; flex-grow: 1; /* Height will be distributed evenly */ } li:last-of-type { flex: 0 0 100%; /* Last element will have 100% height, thus occupying a new column */ } 

Jsfiddle

+2
source

Source: https://habr.com/ru/post/1245384/


All Articles