HTML Table Alternate Row Color
Applying color only to the rows of odd or even numbers in a table is called HTML alternate row color. So, if you don’t know to set alternate table row colors in HTML, don’t worry this article is for you. Use below CSS syntax to set the background color only for odd rows in the table:
Syntax:
tr:nth-child(odd){
declaration list;
}
Ex:
<table border="1px" cellpadding="10px">
<tr align="center"><th>Name</th>
<th>Work</th>
<th>Company</th>
</tr>
<tr><td>John</td>
<td>Manager</td>
<td>Infosys</td>
</tr>
<tr><td>Joe</td>
<td>Team Leader</td>
<td>Zoho</td>
</tr>
<tr><td>Bob</td>
<td>HR</td>
<td>Infosys</td>
</tr>
<tr><td>Sam</td>
<td>Manager</td>
<td>Jio</td>
</tr>
<tr><td>Leo</td>
<td>Fresher</td>
<td>Airtel</td>
</tr>
</table>
Here, we have created a HTML table with 6 rows and 3 columns using <table>, <tr>, and <td> tags. So, the expected output:
If you want to set the background-color only for the odd rows, we need to set the background color using the below steps. Let’s create the alternative row color follow these steps:
CSS:
tr:nth-child(odd){
background-color: lightblue;
}
Expected Output:
- Here first, we selected the <tr> element then used the “nth-child()” selector and passed the “odd” value. If you want to color an even row table then you should pass the parameter value as even.
- Here we give odd as a parameter so, It selects all the odd numbers of <tr> elements.
- Inside the selection, we set “background-color” to “light blue”. You can set any background-color using coloname, hexcode, RGB(), rgba(), etc.
- See, the above output our alternative row background color is set perfectly.