Css Zebra Striping
Zebra stripe divs using pure CSS with the :nth-child() pseudo-class.
1. Basic Zebra Striping (Even/Odd)
If you have a set of divs inside a container, you can target every second div using the even or odd keywords.
/* Stripes the 2nd, 4th, 6th, etc. */
.row:nth-child(even) {
background-color: #f2f2f2;
}
/* Stripes the 1st, 3rd, 5th, etc. */
.row:nth-child(odd) {
background-color: #ffffff;
}
2. The HTML Structure
This works regardless of whether the divs are stacked vertically or lined up horizontally in a row.
<div class="container">
<div class="row">Row 1</div>
<div class="row">Row 2</div>
<div class="row">Row 3</div>
<div class="row">Row 4</div>
</div>
Advanced Variations
Using :nth-of-type()
If you have other elements (like <h1> or <span>) mixed inside the same parent container, use :nth-of-type to ensure the striping only counts the divs:
div:nth-of-type(even) {
background-color: #eee;
}
Custom Patterns (Every 3rd, 4th, etc.)
If you want a stripe every 3rd element, you can use the An+B formula:
/* Every 3rd element */
.row:nth-child(3n) {
background-color: yellow;
}
Highlighting the Hover State
It is common practice to add a hover effect to striped rows to make them easier to read:
.row:nth-child(even) {
background-color: #f9f9f9;
}
.row:hover {
background-color: #e0f0ff; /* Highlights the row you are looking at */
}
Why use this?
- Performance: CSS is much faster than using JavaScript to loop through elements.
- Maintenance: If you add or remove a div, the stripes update automatically (unlike manually adding a
.grayclass to every other div). - Clean Code: Keeps your HTML free of "presentational" classes.