Highlight HTML Table Alternate Rows

Sometime we have to highlight the alternate rows of html table to get the attention of user on important data. There are many ways to highlight the alternate rows but easiest way is using the CSS style selector which does not required any scripting code such as JavaScript or jQuery.

The CSS provides the nth-child() selector which supports the odd and even keyword also its supports the arithmetic operators

Syntax

:nth-child(number) {
  css declarations;
}

Use of selector

 we can use :nth-child selector as follows along with the html tags

//odd keyword
th:nth-child(odd) {
  background: red;
}
//even keyword
p:nth-child(even) {
  background: blue;
}
//arithmetic operator
p:nth-child(4n+0) {
  background: blue;
}

Example

Let's consider we have employee table and we want to highlight the alternate rows

Step 1: Create the CSS Style 

Define the following stylesheet in the head section of your HTML page using the nth-child selector for table

<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 2px solid #DFFF00;
  text-align: left;
  padding: 8px;
}
tr:nth-child(even) {
  background-color: #DFFF00;
}
</style>

Step 2: Create the HTML Table

<h2>Employee</h2>

<table>
  <tr>
    <th>Name</th>
    <th>City</th>
    <th>Address</th>
  </tr>
 
 <tr>
    <td>Vithal Wadje</td>
    <td>Latur</td>
    <td>India</td>
  </tr>
   <tr>
    <td>Sudhir Wadje</td>
    <td>Pune</td>
    <td>India</td>
  </tr>
 <tr>
    <td>Vishal</td>
    <td>New York</td>
    <td>USA</td>
  </tr>
  <tr>
    <td>Kapil</td>
    <td>London</td>
    <td>UK</td>
  </tr>
</table>

The output of the above code will be look like as follows


Summary

Hope this article is useful to learn how to highlight HTML table alternate rows using the CSS, if you have any suggestion then please send using the comment box.

Post a comment

www.CodeNirvana.in

Protected by Copyscape Online Copyright Protection
Copyright © Compilemode