Home > Web Front-end > CSS Tutorial > Can CSS Style Alternate Table Rows Without Using Class Attributes on Each Row?

Can CSS Style Alternate Table Rows Without Using Class Attributes on Each Row?

Patricia Arquette
Release: 2024-12-17 14:24:11
Original
790 people have browsed it

Can CSS Style Alternate Table Rows Without Using Class Attributes on Each Row?

Using CSS to Alternate Table Row Color

When it comes to styling tables, creating alternate row colors is a common task. Traditionally, using class attributes for table rows (TR) is a popular approach, as seen in the example provided:

tr.d0 td {
  background-color: #CC9999;
  color: black;
}
tr.d1 td {
  background-color: #9999CC;
  color: black;
}
Copy after login

However, this method can become tedious when dealing with larger tables. So, can we use CSS to style alternates rows without class attributes?

Styling with a Table Class

The answer is yes. Using a class attribute for the table itself (table.alternate_color), we can achieve the same result as using class attributes for each row:

table.alternate_color tbody tr:nth-child(odd) {
  background-color: #CC9999;
  color: black;
}
table.alternate_color tbody tr:nth-child(even) {
  background-color: #9999CC;
  color: black;
}
Copy after login

This method provides flexibility, allowing you to easily modify the styling of both odd and even rows.

Using jQuery

Another approach involves using jQuery to manipulate the table's rows. This solution is suitable if you want more control over the rendering process:

$(document).ready(function() {
  $("tr:odd").css({
    "background-color": "#000",
    "color": "#fff"
  });
});
Copy after login

Alternative Row Color Using CSS nth-child

Additionally, you can use the CSS nth-child selector to specify the styling for alternate rows:

tbody tr:nth-child(odd) {
  background-color: #4C8BF5;
  color: #fff;
}
Copy after login

By utilizing these techniques, you can create dynamic and visually appealing tables with alternate row colors using CSS.

The above is the detailed content of Can CSS Style Alternate Table Rows Without Using Class Attributes on Each Row?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template