Monday, 17 November 2014

How to apply alternate background color for rows of an HTML table using CSS

In some cases you may want to apply alternate background color for each row of an HTML table.Using CSS3 it is easy to apply alternate color for rows in an HTML table.

Create styles using CSS3 and specify background color by using nth-child(even) and nth-child(odd) selectors.


You can see the CSS3 implementation of the above problem here.

alternatecolorcss.php
<html>
    <head>       
        <title>Alternative color for rows in HTML table using CSS</title>
       
       
<style type="text/css">
    .altcolor{
        width:50%;
        border-collapse:collapse;
    }
    .altcolor td{
        padding:7px; border:#ECD23F 1px solid;
    }
        .altcolor th{
        padding:7px; border:#ECD23F 1px solid;
    }
   
    .altcolor tr{
        background: #ECD23F;
    }
   
    .altcolor tr:nth-child(odd){
        background: #ECD23F;
    }
   
    .altcolor tr:nth-child(even){
        background: #ffffff;
    }
</style>

    </head>
    <body>
   
    <table  class="altcolor">
           <tr bgcolor=#CDCAA9>
               <th>Sl. No</th>
               <th width="300">Item Name</th>
           </tr>
          
            <?php          
                for ($i=1;$i<=10;$i++){                       
                        echo "<tr>";                   
                            echo "<td>$i</td>";
                            echo "<td>Item $i</td>";
                        echo "</tr>";              
                }           
            ?>
          
       </table>


    </body>
</html>




Following is the output of the above code


















See also
How to apply alternate background color for rows of an HTML table using PHP

No comments:

Post a comment