Friday, 13 September 2013

Coloring alternate rows of a HTML table

A table containing large number of rows can be visually represented in a better way by coloring alternate rows in different (often contrasting) colors. The rows can be styled using the CSS selectors. Let's see an example of this:

<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="utf-8">
<title>Selecting Alternate Table Rows</title>
<style>
    table {border-collapse: collapse;}
    th, td {border: 1px solid gray; padding: 5px;}
    tr:nth-child(2n+2) {background: #E1F5A9;}
    tr:nth-child(2n+3) {background: #CEECF5;}
    tr:first-child{background: #F6CECE;}
    
</style>
</head>
<body>

<h1>CSS Table Row Selectors</h1>

<table>
    <tr>
        <td>Col 1</td> <td>Col 2</td> <td>Col 3</td>
    </tr>
    
    <tr>
        <td>One</td> <td>Two</td> <td>Three</td>
    </tr>
    
     <tr>
        <td>Asia</td> <td>Africa</td> <td>Europe</td>
    </tr>
    
     <tr>
        <td>Summer</td> <td>Winter</td> <td>Spring</td>
    </tr>
     
     <tr>
        <td>Cricket</td> <td>Football</td> <td>Tennis</td>
    </tr>
</table>

</body>
</html>

Here is the output:


No comments:

Post a Comment