![]() |
VOOZH | about |
To set alternate table row colors, we can use the :nth-child() pseudo-class in CSS. This technique helps improve the readability of a table by making it easier to differentiate between rows. In this article, we'll cover how to set alternate row colors using the :nth-child() pseudo-class and provide step-by-step instructions to implement it in your HTML and CSS code.
The :nth-child() selector targets elements based on their position in a group of sibling elements, which in this case refers to table rows (<tr>). You can specify whether you want to style even or odd rows using this pseudo-class.
Syntax:
:nth-child(number) {
// CSS Property
}Where number is the argument that represents the pattern for matching elements. It can be odd, even or in a functional notation.
Syntax:
element:nth-child(even)Syntax:
element:nth-child(odd)Example 1: In this example, we use the :nth-child(even) selector to apply a light green background to even-numbered rows, enhancing readability.
Output:
Example 2: In this example, we use the :nth-child(odd) selector to apply a light green background to odd-numbered rows, providing a visual distinction between the rows.
Output:
Supported Browser: