Introduction
Sometimes, we have to highlight the alternate rows of an HTML table to get the attention of the user on important data. There are many ways to highlight the alternate rows, but the easiest way is using the CSS style selector which does not require any scripting code such as JavaScript or jQuery.
The CSS provides the nth-child() selector which supports the odd and even keyword. It also supports arithmetic operators
Syntax
- :nth-child(number) {
- css declarations;
- }
Use of selector
We can use :nth-child selector as it follows along with HTML tags.
-
- th:nth-child(odd) {
- background: red;
- }
-
- p:nth-child(even) {
- background: blue;
- }
-
- p:nth-child(4n+0) {
- background: blue;
- }
Example
Let's consider we have an 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 the 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 the following:
Summary
I hope this blog was useful to learn how to highlight HTML table alternate rows using CSS. If you have any suggestions, then please send them using the comment box.