Page Widget How to - Assign alternative color for table rows using CSS3








Question

We would like to know how to assign alternative color for table rows using CSS3.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
<!--from w ww . j a  v  a  2 s . c  o  m-->
#odd tr:nth-child(odd) {
   background-color: blue;
}
#even tr:nth-child(even) {
   background-color: red;
}
  </style>

</head>
<body>
  <table id="odd">
    <tr>
        <td>IE</td>
        <td>test</td>
    </tr>
    <tr>
        <td>Firefox</td>
        <td>test</td>
    </tr>
    <tr>
        <td>Chrome</td>
        <td>test</td>
    </tr>
    <tr>
        <td>Safari</td>
        <td>test</td>
    </tr>
    <tr>
        <td>Opera</td>
        <td>test</td>
    </tr>
</table>
<table id="even">
    <tr>
        <td>IE</td>
        <td>test</td>
    </tr>
    <tr>
        <td>Firefox</td>
        <td>test</td>
    </tr>
    <tr>
        <td>Chrome</td>
        <td>test</td>
    </tr>
    <tr>
        <td>Safari</td>
        <td>test</td>
    </tr>
    <tr>
        <td>Opera</td>
        <td>test</td>
    </tr>
</table>
</body>
</html>

The code above is rendered as follows: