HTML5 and CSS3, Second Edition

(singke) #1
css3_advanced_selectors/stylesheets/style.css
th{
background-color:#000;
color:#fff;
}

Apply that style, and the table looks like this:


With the table’s borders and spacing cleaned up, we can start using the pseudo-
classes to style individual rows and columns. We’ll start by striping the table.

Striping Rows with :nth-of-type


We’ve all seen “zebra striping” in tables. It’s useful because it gives users
horizontal lines to follow. This kind of styling is best done in CSS, the presen-
tation layer. That has traditionally meant introducing additional class names
to our table rows, like “odd” and “even.” We don’t want to pollute our table’s
markup like that, because the HTML5 specification encourages us to avoid
using class names that define presentation. Using some new selectors, we
can get what we want without changing our markup at all, truly separating
presentation from content.

The nth-of-type selector finds every nth element of a specific type using either
a formula or keywords. We’ll get into the formula in more detail soon, but
first let’s focus on the keywords, because they’re easier to grasp immediately.

We want to stripe every other row of the table with a different color, and the
easiest way to do that is to find every even row of the table and give it a
background color. We then do the same thing with the odd rows. CSS3 has
even and odd keywords that support this exact situation.

css3_advanced_selectors/stylesheets/style.css
tr:nth-of-type(even){
background-color:#F3F3F3;
}
tr:nth-of-type(odd) {
background-color:#ddd;
}

report erratum • discuss

Styling Tables with Pseudoclasses • 71


Download from Wow! eBook <www.wowebook.com>

Free download pdf