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