Styling alternate rows of a table using CSS selectors can be achieved by utilizing the :nth-child() pseudo-class. This powerful selector allows us to target specific elements within a parent container based on their position in the hierarchy. By combining this selector with the even or odd keyword, we can easily apply different styles to alternate rows of a table.
To begin, let's assume we have a simple HTML table structure like this:
html
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
<tr>
<td>Data 4</td>
<td>Data 5</td>
<td>Data 6</td>
</tr>
<tr>
<td>Data 7</td>
<td>Data 8</td>
<td>Data 9</td>
</tr>
</table>
To style the alternate rows, we can use the :nth-child() pseudo-class in combination with the odd or even keyword. The following CSS code demonstrates how to apply different background colors to alternate rows:
css
tr:nth-child(odd) {
background-color: #f2f2f2;
}
tr:nth-child(even) {
background-color: #ffffff;
}
In this example, the :nth-child(odd) selector targets all odd-numbered rows, while the :nth-child(even) selector targets all even-numbered rows. By applying different background colors to these selectors, we can visually distinguish alternate rows in the table.
It's worth noting that the :nth-child() selector is 1-based, meaning the first row is considered odd, the second row is even, and so on. If you want to exclude the table header row from the styling, you can use the :nth-child() selector with a starting index greater than 1. For example:
css
tr:nth-child(2n+3) {
background-color: #f2f2f2;
}
tr:nth-child(2n+4) {
background-color: #ffffff;
}
In this case, the styling will start from the third row, applying the background color to every second row.
By utilizing the :nth-child() pseudo-class in CSS, we can easily style alternate rows of a table, enhancing the visual presentation and readability of tabular data.
Other recent questions and answers regarding Examination review:
- How do you align table header text and table data in HTML tables?
- How can you add borders to a table using CSS?
- What is the purpose of the TR tag in HTML tables?
- How do you create a table structure in HTML using the table tag?

