Home > database >  CSS - How can I divide a list <li> in 3 collumns using li:nth-child?
CSS - How can I divide a list <li> in 3 collumns using li:nth-child?

Time:05-13

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

CodePudding user response:

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>

CodePudding user response:

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 >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
</div>

  • Related