How to Make a Zebra Striped Table With CSS 3

Using nth-of-type(N) With Tables

Pattern of black and white lines
Rian Hughes/Stockbyte/Getty Images

One of the most common ways to style tables is to set the background color of every other row. This is often referred to as "zebra stripes". This type of striping makes the table much easier to read. But it requires that you add a class to every other table row and then set styles for them.

This works fine, but every time you need to edit that table, you may have to edit every single row in the table to get the classes correct.

For example, if you add a new row to your table, every other row below it needs to have the class changed.

But CSS 3 makes it easy to style tables with zebra stripes. You don't need to add any extra HTML attributes or CSS classes, you just use the nth-of-type CSS pseudo-class.

Write Your HTML Table

First, write your table as you would normally write it in HTML. Don't add any special classes to the rows or columns.


  
    
    
    
    
  
  
    
    
    
    
  
  
    
    
    
    
  
  
    
    
    
    
  
  
    
    
    
    
  
test test testtest test testtest test testtest test test
test test testtest test testtest test testtest test test
test test testtest test testtest test testtest test test
test test testtest test testtest test testtest test test
test test testtest test testtest test testtest test test

Then Add the CSS Pseudo-Class

In your stylesheet, add the following CSS:

tr:nth-of-type(odd) {
  background-color:#ccc;
}

This will style every other row with a gray background color starting with the first row.

See the zebra striped table.

You Can Also Style Every Other Column in the Same Way

Instead of tr, change your style to td. For example:

td:nth-of-type(odd) {
  background-color:#ccc;
}

See the zebra striped columns.

Format
mla apa chicago
Your Citation
Kyrnin, Jennifer. "How to Make a Zebra Striped Table With CSS 3." ThoughtCo, May. 22, 2017, thoughtco.com/zebra-striped-table-in-css3-3466982. Kyrnin, Jennifer. (2017, May 22). How to Make a Zebra Striped Table With CSS 3. Retrieved from https://www.thoughtco.com/zebra-striped-table-in-css3-3466982 Kyrnin, Jennifer. "How to Make a Zebra Striped Table With CSS 3." ThoughtCo. https://www.thoughtco.com/zebra-striped-table-in-css3-3466982 (accessed December 16, 2017).