How to Style Even/Odd Elements in CSS?

You can select and style even/odd elements using the nth-child() CSS pseudo-class in the following two ways:

  1. Using keyword values;
  2. Using functional notation.

Using Keyword Values

You can use the even or odd keywords with nth-child() to select even/odd elements in a group of siblings like so:

li:nth-child(even) {}
li:nth-child(odd) {}

This is the preferred way of doing this since it is more readable.

Using Functional Notation

You can pass in the following arguments to nth-child() to select even/odd elements in a group of siblings:

li:nth-child(2n) {} /* even */
li:nth-child(2n+1) {} /* odd */

Where:

  • n represents non-negative integers starting from 0;
  • The number before n represents the integer step size;
  • The number followed by + symbol (as you can see with the selector for odd numbers) represents the integer offset number, which is optional.

Perhaps the following table would help you better visualize the way these selectors work:

n 2n 2n+1
0 0 [=(2 * 0)] 1 [=(2 * 0) + 1]
1 2 [=(2 * 1)] 3 [=(2 * 1) + 1]
2 4 [=(2 * 2)] 5 [=(2 * 2) + 1]
... ... ...

Please note that the matching of elements in a group of siblings starts from one. Therefore, the first matched element would be odd.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.