Home > Web Front-end > CSS Tutorial > How Can I Create Alternating Row Colors in HTML Tables Using CSS and JavaScript?

How Can I Create Alternating Row Colors in HTML Tables Using CSS and JavaScript?

Susan Sarandon
Release: 2025-01-02 13:38:39
Original
207 people have browsed it

How Can I Create Alternating Row Colors in HTML Tables Using CSS and JavaScript?

Achieving Alternate Table Row Colorization with CSS

In HTML tables, assigning alternating colors to rows can enhance visual appeal, making data more readable. This can be achieved using either CSS classes applied to individual tr elements or by styling the table element itself.

Using CSS Classes

The provided HTML and CSS utilize CSS classes (tr.d0 and tr.d1) to color rows. However, to color rows based on their position within the table, we can leverage the :nth-child selector within the tbody element. For instance:

tbody tr:nth-child(2n+1) {
  background-color: #CC9999;
  color: black;
}
tbody tr:nth-child(2n) {
  background-color: #9999CC;
  color: black;
}
Copy after login

Using Table Styling

Alternatively, we can style the entire table using the table element. To make all odd rows a specific color, we can utilize the following CSS:

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

Using JavaScript (jQuery)

Another approach involves using JavaScript (jQuery):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Copy after login
$(document).ready(function() {
  $("tr:odd").css({
    "background-color": "#000",
    "color": "#fff"
  });
});
Copy after login

The above is the detailed content of How Can I Create Alternating Row Colors in HTML Tables Using CSS and JavaScript?. 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