HTML table with alternate color rows

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.
table-with-alternate-color-rows

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>
refresh

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>
refresh

Comparing css3 vs jQuery approach

  1. 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.
  2. jQuery approach has to be re run in case a row is added dynamically in the middle.
  3. Row with th (header) is also considered as a row when deciding even/odd.
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments