'CSS - How can I divide a list <li> in 3 columns using li:nth-child?
There are 6 elements and I want them to be something like that:
- First - Third - Fifth
- Second - Fourth - Sixth
I tried something like this:
li:nth-child(6n+1) {
float: left;
width: 30%;
}
li:nth-child(2n+3) {
float: right;
width: 30%;
}
Solution 1:[1]
You can use CSS grid like below:
ul {
display: grid;
list-style: none;
grid-auto-flow: column;
grid-template-rows: 1fr 1fr;
margin:0;
padding:0;
text-align:center;
}
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
<li>five</li>
<li>six</li>
</ul>
Solution 2:[2]
Here's an example of that layout using CSS Grid; as @NickG mentioned, it's worth reading up on the documentation, as it's a really useful concept to learn.
Below, I've assigned each div a grid-area
name, and used that to reference the layout you described with grid-template-areas
.
.container { display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr;
gap: 8px 8px;
grid-auto-flow: row;
grid-template-areas:
"one three five"
"two four six";
}
.container * {
width: 50px;
height: 50px;
background: orange;
}
.one { grid-area: one; }
.two { grid-area: two; }
.three { grid-area: three; }
.four { grid-area: four; }
.five { grid-area: five; }
.six { grid-area: six; }
<div class="container">
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
<div class="five">5</div>
<div class="six">6</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Temani Afif |
Solution 2 | Marco |