Styling Striped Lists in CSS
As part of my blog rewrite, I wanted to create a striped list effect for my sidebars, something like this:
In this post I'll show how we can take a regular unordered list and style it with stripes using CSS. As an example, here's a simple list of items:
<ul>
<li>Apples</li>
<li>Oranges</li>
<li>Bananas</li>
<li>Pears</li>
<li>Plums</li>
</ul>
By default, this will render with bullet points and some indentation:
Let's give our ul
a class of striped-list
, and then we can clear the default formatting like this:
ul.striped-list {
list-style-type: none;
margin: 0;
padding: 0;
}
This gets rid of the bullet points and indentation:
Next, let's introduce the striping. That's easy thanks to the CSS :nth-of-type()
selector. We'll give every odd
numbered row a background-color
:
ul.striped-list > li:nth-of-type(odd) {
background-color: #e9e9f9 ;
}
We're almost there already:
But we could do with some extra padding on li
elements and I'd also like a dividing line between list elements. We can do that by giving each li
some padding, and putting a one pixel bottom border on each li
:
ul.striped-list > li {
border-bottom: 1px solid rgb(221,221,221);
padding: 6px;
}
Now we're almost there but if you look very carefully you'll see that the bottom item in the list has a border, and I only wanted to use the border as a separator between items. We can get rid of that with the help of the CSS :last-child()
selector, turning off the border on the last li
element only.
ul.striped-list > li:last-child {
border-bottom: none;
}
And this gives us the desired effect:
Of course, I'm sure this is all very basic stuff if you already know CSS, but hope someone finds this useful. You can play with a full example on CodePen.