00 Votes

CSS: Colorize Table Rows Alternately only with CSS

Tutorial by Stefan Trost | Last update on 2023-06-19 | Created on 2012-05-28

For tables without border, it can often be quite helpful, to color the rows of the table alternately in a different color, so that a line is easier to read and the whole table looks clearer.

One example we can see here:

Row 1Color AText
Row 2Color BText
Row 3Color AText
Row 4Color BText
Row 5Color AText

If we would like to implement the example on our website, the problem occurs, that it can take forever sometimes to color all of these table rows by hand with the appropriate design rules. Especially when we are running a website that contains many tables and we are also changing these table regularly, it means a lot of work.

Fortunately, there is a solution, how we can solve the entire problem by using CSS.

Format Table Rows with CSS

Let's have a look at the following CSS rules:

tr:nth-child(even) {
   background-color: #FD9D5D;
tr:nth-child(odd) {
   background-color: #C0F390;
table {
   border-spacing: 0px;

The CSS selector nth-child makes it possible to select the nth occurrence of an element. In the example, we refer to the tr element that is our table row. We use "even" to assign a color to all even occurences of the element and we use "odd" to assign another color to all odd occurences of the element. With this, we achieve our alternate coloring of the lines. Of course, we can also assign only the "even" or the "odd" lines to make the other lines looking like the background.

In addition, we set the border-spacing of all tables to 0 pixels. This causes, that the unsightly "hyphens" between the individual cells of the table will not occur. If you want them, however, you can simply omit this CSS rule, of course.

Browser Support

The required CSS selector nth-child is supported by the browsers Opera, Chrome, Safari, Firefox (from version 3.5) and Internet Explorer (unfortunately only from version 9). The old Internet Explorer versions 6, 7 and 8, which unfortunately are sometimes still in use, do not support the selector. In these browsers, the rows appear uncolored.

In the event, that you are creating the table dynamically with PHP, you can use the tip Colorize Table Rows Alternately with PHP. This tip explains how to color the rows in a table with PHP, which will then be visible in all browser versions.


About the Author

AvatarYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile


Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.


Ask your own question or write your own article on askingbox.com. That’s how it’s done.