How to set alternative table row color in CSS?

It is a short tutorial table CSS styles on how to change row color

  • How to change alternative row colors in a table?
  • How to change the first-row color in the table?
  • How to set the last row color in the table

In the Html table,

The table represents with the <\table\> tag The row represented with tr tag the column represents with td, and th for header columns

How to change alternative row colors and styles in the HTML table

What is the alternative row color in the HTML table? alternative rows represent even and odd numbers, if we have two rows, one row represents one color and another row has a 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 an even-numbered row.

In CSS, :nth-child selector represents the even and odd-numbered rows.

The nth-child selector selects the nth-child element.

Syntax

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

Here is an event with odd rules In this example,

The changed background color of a 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 the tr tag

You can use it to generate these 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;
}

It is a Legacy and old way of doing this.

You can use nth-child pseudo-selectors and It supports all the latest browsers.

How to change first-row color in an HTML table

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

Syntax

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

How to change the last row color in the 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 a custom class for the navigation bar.

See the Pen