Home > Mobile >  CSS nth-child formula
CSS nth-child formula

Time:09-28

I have a list with a variable number of list items. I want to achieve a certain style pattern with the items in the list as such:

Item 1: color: green
Item 2: color: orange
Item 3: color: green
Item 4: color: orange
Item 5: color: orange
Item 6: color: green
Item 7: color: orange
Item 8: color: green
Item 9: color: green
Item 10: color: orange
Item 11: color: green
Item 12: color: orange
...
Item 99:

The pattern is an even/odd that switches every 4 items. Is there an nth-child formula I can use that handles any number of list items?

li:nth-child(?) {
  color: green;
}

li:nth-child(?) {
  color: orange;
}

<ul>
  <li>Green Item</li>
  <li>Orange Item</li>
  <li>Green Item</li>
  <li>Orange Item</li>
  <li>Orange Item</li>
  <li>Green Item</li>
  <li>Orange Item</li>
  <li>Green Item</li>
  <li>Green Item</li>
  <li>Orange Item</li>
  <li>Green Item</li>
  <li>Orange Item</li>
</ul>

CodePudding user response:

You can achieve this effect via CSS if the formula can be simplified enough to be explained as a pattern via modulo (remaining numbers after division)

Some good examples here in this thread

However, making it dynamic for future items might be a pain, so I would highly recommend checking out SASS (might be a good opportunity to learn) as you can make much more advanced calculations that get outputted to CSS at the end

Sass examples here

CodePudding user response:

Your pattern repeat each 8 items so:

li:nth-child(8n   1),
li:nth-child(8n   3),
li:nth-child(8n   6),
li:nth-child(8n   8){
  color: green;
}

li:nth-child(8n   2),
li:nth-child(8n   4),
li:nth-child(8n   5),
li:nth-child(8n   7){
  color: orange;
}
<ul>
  <li>Green Item</li>
  <li>Orange Item</li>
  <li>Green Item</li>
  <li>Orange Item</li>
  <li>Orange Item</li>
  <li>Green Item</li>
  <li>Orange Item</li>
  <li>Green Item</li>
  <li>Green Item</li>
  <li>Orange Item</li>
  <li>Green Item</li>
  <li>Orange Item</li>
</ul>

That you can simplify using one color as the default one:

li {
  color: green;
}

li:nth-child(8n   2),
li:nth-child(8n   4),
li:nth-child(8n   5),
li:nth-child(8n   7){
  color: orange;
}
<ul>
  <li>Green Item</li>
  <li>Orange Item</li>
  <li>Green Item</li>
  <li>Orange Item</li>
  <li>Orange Item</li>
  <li>Green Item</li>
  <li>Orange Item</li>
  <li>Green Item</li>
  <li>Green Item</li>
  <li>Orange Item</li>
  <li>Green Item</li>
  <li>Orange Item</li>
</ul>

  • Related