How to set alternative table row color in CSS?


This is an short tutorial table css styles for row color change for below thing

  • How to change alternative row color in table?
  • How to change first row color in table?
  • How to set last row color in table

In Html table,

Table is represented with <\table\> tag Row is represented with tr tag column is represented with td, and th for header columns

How to change alternative row color and styles in html table

What is alternative row color in html table? alternative rows are represented with even and odd numbers, if we have two rows, One row represents one colro and another row has different color.

For example, 1,3,5,7 up to n represents one set called odd numbered row 2,4,6,8 up to n tells even numbered row.

In CSS, :nth-child selector is used to represent the even and odd numbered rows.

nth-child selector selects the nth child element.

Syntax

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

Here is an event odd rules In this example,

Changed background-color of an table row to grey for even rows background-color changed to white for odd rows.

tr:nth-child(even){
    background-color:#f0f0f0;

}
tr:nth-child(odd){
    background-color:#ffff;

}

Another way is to add class selectors for even and odd rows We have added roweven and rowodd css selectors for tr tag

You can use to generate this class selectors using javascript or any programming language.

<table style="width:100%">
  <tr>
    <th>Id</th>
    <th>Name</th>
    <th>Salary</th>
  </tr>
  <tr class="rowodd">
    <td>11</td>
    <td>John</td>
    <td>5000</td>
  </tr>
  <tr class="roweven">
    <td>2</td>
    <td>Andrew</td>
    <td>6000</td>
  </tr>
  <tr class="rowodd">
    <td>3</td>
    <td>Eric</td>
    <td>9000</td>
  </tr>
  <tr class="roweven">
    <td>4</td>
    <td>Mark</td>
    <td>10000</td>
  </tr>
  <tr class="rowodd">
    <td>5</td>
    <td>Jain</td>
    <td>4000</td>
  </tr>
</table>

And css styles

.rowodd{
    background-color:#ffff;
    }
.roweven{
    background-color:#f0f0f0;
    }

This is an Legacy and old way of doing this.

You can use nth-child psuedo selectors and It supports in all latest browsers.

How to change first row color in a html table

We have to use first-child selector to select the first row tr tag

Syntax

:first-child{
    css styles
}
tr:first-child{
  background-color:#9999;

}

How to change last row color in table

We have to use :last-child selector to select the last row of a table.

Syntax

:last-child{
    css styles
}
tr:last-child{
  background-color:#9999;

}

Codepen example

This example is the code for creating custom class for navigation bar

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.