We often need to display a table with alternate rows having different colors. We can do it either using CSS3 nth-child selector or using jQuery.
Alternate color rows using CSS3 nth-child selector
We’ll using nth-child(odd) and nth-child(even) selector.
tr:nth-child(odd) {background-color: gray;} tr:nth-child(event) {background-color: lightgray;}
Here is the code snippet with a simple table and css using nth-child selector for creating alternate color rows table.
<style type="text/css" media="screen"> #t1 tr:nth-child(odd) {background-color: gray;} #t1 tr:nth-child(even) {background-color: lightgray;} </style> <table id="t1"> <tr><th>header1</th><th>header2</th> <tr><td>val11</td><td>val12</td> <tr><td>val21</td><td>val22</td></tr> <tr><td>val31</td><td>val32</td></tr> </table>
Alternate color rows using jQuery
Here is the code snippet using jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript"> $(function() { $("#t1 tr:odd").css("background-color", "gray"); $("#t1 tr:even").css("background-color", "lightgray"); }); </script> <table id="t1"> <tr><th>header1</th><th>header2</th> <tr><td>val11</td><td>val12</td> <tr><td>val21</td><td>val22</td></tr> <tr><td>val31</td><td>val32</td></tr> </table>
Comparing css3 vs jQuery approach
- CSS3 approach may not work with old browsers which do not support CSS3 (e.g. IE8). This is not a big concern though as most popular browsers support CSS3.
- jQuery approach has to be re run in case a row is added dynamically in the middle.
- Row with th (header) is also considered as a row when deciding even/odd.