Highlight HTML Table Alternate Row Colors Using CSS Selector

Introduction

 
Sometimes, we have to highlight the alternate rows of an HTML table to get the attention of the user on important data. There are many ways to highlight the alternate rows, but the easiest way is using the CSS style selector which does not require any scripting code such as JavaScript or jQuery.
 
The CSS provides the nth-child() selector which supports the odd and even keyword. It also supports arithmetic operators
 
Syntax
  1. :nth-child(number) {  
  2.   css declarations;  
  3. }  

Use of selector

 
We can use :nth-child selector as it follows along with HTML tags.
  1. //odd keyword  
  2. th:nth-child(odd) {  
  3.   background: red;  
  4. }  
  5. //even keyword  
  6. p:nth-child(even) {  
  7.   background: blue;  
  8. }  
  9. //arithmetic operator  
  10. p:nth-child(4n+0) {  
  11.   background: blue;  
  12. }  
Example
 
Let's consider we have an employee table and we want to highlight the alternate rows
 
Step 1 - Create the CSS Style
 
Define the following stylesheet in the head section of your HTML page using the nth-child selector for the table.
  1. <style>  
  2. table {  
  3.   font-familyarialsans-serif;  
  4.   border-collapsecollapse;  
  5.   width100%;  
  6. }  
  7.   
  8. td, th {  
  9.   border2px solid #DFFF00;  
  10.   text-alignleft;  
  11.   padding8px;  
  12. }  
  13. tr:nth-child(even) {  
  14.   background-color#DFFF00;  
  15. }  
  16. </style>  
Step 2 - Create the HTML Table
  1. <h2>Employee</h2>  
  2.   
  3. <table>  
  4.   <tr>  
  5.     <th>Name</th>  
  6.     <th>City</th>  
  7.     <th>Address</th>  
  8.   </tr>  
  9.    
  10.  <tr>  
  11.     <td>Vithal Wadje</td>  
  12.     <td>Latur</td>  
  13.     <td>India</td>  
  14.   </tr>  
  15.    <tr>  
  16.     <td>Sudhir Wadje</td>  
  17.     <td>Pune</td>  
  18.     <td>India</td>  
  19.   </tr>  
  20.  <tr>  
  21.     <td>Vishal</td>  
  22.     <td>New York</td>  
  23.     <td>USA</td>  
  24.   </tr>  
  25.   <tr>  
  26.     <td>Kapil</td>  
  27.     <td>London</td>  
  28.     <td>UK</td>  
  29.   </tr>  
  30. </table>  
The output of the above code will be look like the following:
 
Highlight HTML Table Alternate Rows Colour Using CSS Selector
 

Summary

 
I hope this blog was useful to learn how to highlight HTML table alternate rows using CSS. If you have any suggestions, then please send them using the comment box.