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
Susan SarandonOriginal
2025-01-02 13:38:39241browse

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;
}

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;
}

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>
$(document).ready(function() {
  $("tr:odd").css({
    "background-color": "#000",
    "color": "#fff"
  });
});

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!

Statement:
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