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

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

Barbara Streisand
Release: 2024-12-21 09:36:10
Original
879 people have browsed it

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

Using CSS to Create Alternating Table Row Colors

To dynamically alternate the background colors of table rows with CSS, you can manipulate the CSS properties of table and row elements.

Using the nth-child Selector:

You can use the CSS nth-child selector to target odd or even rows. For example:

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

This rule will style all odd rows in the table body with a blue background and white text.

Using jQuery:

Alternatively, you can use JavaScript to identify and style rows dynamically. With jQuery:

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

This code selects all odd rows and sets their background color to black and text color to white.

Applying Styles to the Table Element:

If you want to apply the alternating color effect to the entire table, you can use this approach:

<table class="alternate_color">
  ...
</table>

.alternate_color tr:nth-child(odd) {
  background-color: #f5f5f5;
}
Copy after login

In this case, you add a class to the table, and the CSS rule targets all odd rows within that table.

Note: Using the table element's class for alternating row colors may interfere with existing styling rules applied to the table, so it's generally preferred to use the nth-child selector directly on the tr element.

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