Home >Web Front-end >CSS Tutorial >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; }
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" }); });
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; }
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!