When it comes to styling tables, creating alternate row colors is a common task. Traditionally, using class attributes for table rows (TR) is a popular approach, as seen in the example provided:
tr.d0 td { background-color: #CC9999; color: black; } tr.d1 td { background-color: #9999CC; color: black; }
However, this method can become tedious when dealing with larger tables. So, can we use CSS to style alternates rows without class attributes?
The answer is yes. Using a class attribute for the table itself (table.alternate_color), we can achieve the same result as using class attributes for each row:
table.alternate_color tbody tr:nth-child(odd) { background-color: #CC9999; color: black; } table.alternate_color tbody tr:nth-child(even) { background-color: #9999CC; color: black; }
This method provides flexibility, allowing you to easily modify the styling of both odd and even rows.
Another approach involves using jQuery to manipulate the table's rows. This solution is suitable if you want more control over the rendering process:
$(document).ready(function() { $("tr:odd").css({ "background-color": "#000", "color": "#fff" }); });
Additionally, you can use the CSS nth-child selector to specify the styling for alternate rows:
tbody tr:nth-child(odd) { background-color: #4C8BF5; color: #fff; }
By utilizing these techniques, you can create dynamic and visually appealing tables with alternate row colors using CSS.
The above is the detailed content of Can CSS Style Alternate Table Rows Without Using Class Attributes on Each Row?. For more information, please follow other related articles on the PHP Chinese website!