How to Create Alternating Background Colors in Table Rows With CSS
In larger tables it is often an aid to reading to have alternating background colors for every other row in the table. It can help readers follow lines across the table. It is easy to implement with CSS. Here is how.
- Difficulty:
- Easy
Instructions
-
-
1
A table with alternating colors on the rows
Here's a simple table with alternating gray and white rows. This technique will work for any color scheme or any size table.
-
2
Build the table using your normal HTML table-building tools.
-
3
In the stylesheet, create a class that can be applied to alternating TR (table row) elements. Here's an example:
.rowcolor {
background: #CCCCCC;
} -
4
Use the class on the TR elements
In the HTML, add the class to alternating rows in your table. Apply it to the TR element. See image for example.
-
5
If you would like to have a different color for the row of the table that contains the headings, you can create a new class or id rule in your stylesheet that will only apply a background color to the TH elements.
-
1
Tips & Warnings
The table pictured above is using the "border-collapse:collapse" rule to remove the empty space between the table borders.