Style child elements in a repeatable pattern in CSS

Mark O'Neill
March 1, 2021

You can use existing CSS selectors to style element in a list in various different ways. Using this method you can select odd numbers, even numbers and also when specific styles start.

copy code
css
/* Position 1, 3, 5, etc. */
p:nth-child(odd) {
  background: red;
}

/* Position 2, 4, 6, etc. */
p:nth-child(even) {
  background: blue;
}

/* Every third child starting at position 0 */
p:nth-child(3n+0) {
  background: green;
}

/* Every 4th element starting from position 3 */
p:nth-child(4n+3) {
  background: aqua;
}
Know a better answer? Join our our community and let us know.