CSS3: Adding Color to Tables and Lists Using Pseudo-Classes

By Michael Rohde

Here are a couple of CSS3 techniques that can help you format lists and tables, especially if your site tends to have long lists and you don't like using traditional bullets. The problem with long lists is that they become monotonous rather quickly. Hopefully, a bit of CSS3 will help improve the style of the list.

The CSS3 E:nth-child(n) Pseudo-Class

This article will explore possible uses of the E:nth-child(n) pseudo-class. What is a pseudo-class, you ask? W3schools.com provides this definition, "CSS pseudo-classes are used to add special effects to some selectors." These pseudo-classes are not vendor specific and there are 16 of them listed in the latest W3C spec. The code in this article does work with the latest versions of Firefox, Chrome and Internet Explorer.

Let's start by adding background colors to every other item in a long bullet list. Here's how the bullet list looks like without the bullets:


As you can see, the list runs together without any style or form. Let's see if adding a background color to every odd item helps improve the aesthetics. In your CSS, use this:

ul li:nth-child(odd) {
background-color: #999;
color: #fff; }

This only formats the odd rows. You'll immediately notice that you'll still have bullets on the even rows. That is easily solved by adding this:

ul li:nth-child(even) {
background-color: #777;
color: #fff; }

Now your list looks like this:

Image 2

It's up to you to decide on colors and fonts. You can apply the same formatting techniques to tables like this:

table tr:nth-child(even) {
background-color: #777;
color: #fff; }

So, your table can go from this:

Image 3

To this:

Image 4

You can also single out a single item in a list or table by doing this:

table tr:nth-child(3) {
background-color: #777;
color: #fff; }

And you get this:

Image 5

The possibilities on how you use this are pretty open. You can even use some complex math to determine which rows are formatted and which are not. This article should provide a good starting point for you to use pseudo-classes and CSS3.

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date