Howdy folks! Today I am going to show you how to achieve zebra striping effect on HTML tables by using various methods. The zebra striping effect is basically used to differentiate each table rows from the previous and next one. Regular tabular data messed up while we read it without adding any kind of style to it. But the zebra striping effect not only looks good but also effectively increases user readability – user friendliness.
The old long boring even-odd method
HTML
<table> <tr class="odd"> <td>a1</td><td>a2</td><td>a3</td> </tr> <tr class="even"> <td>b1</td><td>b2</td><td>b3</td> </tr> <tr class="odd"> <td>c1</td><td>c2</td><td>c3</td> </tr> <tr class="even"> <td>d1</td><td>d2</td><td>d3</td> </tr> <tr class="odd"> <td>e1</td><td>e2</td><td>e3</td> </tr> <tr class="even"> <td>f1</td><td>f2</td><td>f3</td> </tr> </table>
CSS
table, tr, td { border: 1px solid #000; border-collapse: collapse; padding: 10px; } tr.even { background: lime; } tr.odd { background: yellow; }
Result
a1 | a2 | a3 |
b1 | b2 | b3 |
c1 | c2 | c3 |
d1 | d2 | d3 |
e1 | e2 | e3 |
f1 | f2 | f3 |
Explanation
In the code above we have added class “even” on even rows and class “odd” on odd rows – by count in the HTML. Then we selected “tr” tag with “even” class and again “tr” tag with “odd” class. Then we styled them individually. This method is old, long, time-consuming to achieve zebra striping effect. We have to write more and more codes. Now days we – developers are lazy enough, so we are going to use New CSS3 method.
New CSS3 method
HTML
<table> <tr> <td>a1</td><td>a2</td><td>a3</td> </tr> <tr> <td>b1</td><td>b2</td><td>b3</td> </tr> <tr> <td>c1</td><td>c2</td><td>c3</td> </tr> <tr> <td>d1</td><td>d2</td><td>d3</td> </tr> <tr> <td>e1</td><td>e2</td><td>e3</td> </tr> <tr> <td>f1</td><td>f2</td><td>f3</td> </tr> </table>
CSS
table, tr, td { border: 1px solid #000; border-collapse: collapse; padding: 10px; } tr:nth-child(even) { background: #fdf; } tr:nth-child(odd) { background: #dfd; }
Result
a1 | a2 | a3 |
b1 | b2 | b3 |
c1 | c2 | c3 |
d1 | d2 | d3 |
e1 | e2 | e3 |
f1 | f2 | f3 |
Explanation
Selecting rows by custom “n” values in nth-child function
tr:nth-child(2n) { background: #fdf; } tr:nth-child(2n+1) { background: #dfd; }
Note: The value of “n” is number of row starting from zero and it increases by each row from top to bottom on counting.
Calculation of nth-child (equation of “n”)
2n = Select 2nd, 4th, 6th, 8th, etc. even-numbered rows.
2n + 1 = (2 x 0) + 1 = 1st row
2n + 1 = (2 x 1) + 1 = 3rd row
2n + 1 = (2 x 2) + 1 = 5th row
2n + 1 = (2 x 3) + 1 = 7th row
2n + 1 = (2 x 4) + 1 = 9th row
-n + 3 = -0 + 3 = 3rd row
-n + 3 = -1 + 3 = 2nd row
-n + 3 = -2 + 3 = 1st row
-n + 3 = -3 + 3 = 0 (no match)
n | 2n + 1 | 4n + 1 | 4n + 4 | 4n | 5n – 2 | -n + 3 |
---|---|---|---|---|---|---|
0 | 1 | 1 | 4 | – | – | 3 |
1 | 3 | 5 | 8 | 4 | 3 | 2 |
2 | 5 | 9 | 12 | 8 | 8 | 1 |
3 | 7 | 13 | 16 | 12 | 13 | – |
4 | 9 | 17 | 20 | 16 | 18 | – |
5 | 11 | 21 | 24 | 20 | 23 | – |