Sameera Liyanage
Sameera Liyanage

Reputation: 1380

Styling list items by using css :nth-child selector

I have ul list items and i want them to style like following graphic. Is there way to style it by using css nth-child selector or any other way by using only css.

enter image description here

ul, ol {
  list-style: none;
  padding: 0;
}
li {
  text-align: center;
  line-height: 2;
  background: slategrey;
  border:1px solid white;
}
li:nth-child(1) {
  background: lightsteelblue;
}
<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
    <li>Six</li>  
    <li>Seven</li>
    <li>Eight</li>
    <li>Nine</li>
    <li>Ten</li>
    <li>Eleven</li>
    <li>Twelve</li>
    <!--There may be more list items -->
  </ul>

Upvotes: 0

Views: 350

Answers (3)

Joven28
Joven28

Reputation: 769

Why not categorize them with the class? Even though you can do it with the nth-child but it is hard when you want to change something you will also have to change your formula.

ul, ol {
  list-style: none;
  padding: 0;
}
li {
  text-align: center;
  line-height: 2;
  border:1px solid white;
}

li.lightsteelblue {
  background: lightsteelblue;
}

li.slategrey {
  background: slategrey;
}
<ul>
    <li>One</li>
    <li class="lightsteelblue">Two</li>
    <li>Three</li>
    <li>Four</li>
    <li class="slategrey">Five</li>
    <li>Six</li>  
    <li>Seven</li>
    <li>Eight</li>
    <li>Nine</li>
    <li>Ten</li>
    <li>Eleven</li>
    <li>Twelve</li>
    <!--There may be more list items -->
  </ul>

Upvotes: 0

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28445

Use selector li:nth-child(4n), li:nth-child(4n+1)

ul, ol {
  list-style: none;
  padding: 0;
}
li {
  text-align: center;
  line-height: 2;
  background: slategrey;
  border:1px solid white;
}
li:nth-child(4n), li:nth-child(4n+1)  {
  background: lightsteelblue;
}
<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
    <li>Six</li>  
    <li>Seven</li>
    <li>Eight</li>
    <li>Nine</li>
    <li>Ten</li>
    <li>Eleven</li>
    <li>Twelve</li>
    <!--There may be more list items -->
  </ul>

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370679

Use li:nth-child(4n + 1), li:nth-child(4n + 4):

ul, ol {
  list-style: none;
  padding: 0;
}
li {
  text-align: center;
  line-height: 2;
  background: slategrey;
  border:1px solid white;
}
li:nth-child(4n + 1), li:nth-child(4n + 4) {
  background: lightsteelblue;
}
<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
    <li>Six</li>  
    <li>Seven</li>
    <li>Eight</li>
    <li>Nine</li>
    <li>Ten</li>
    <li>Eleven</li>
    <li>Twelve</li>
    <!--There may be more list items -->
  </ul>

Upvotes: 5

Related Questions