HTML5 and CSS3, Second Edition

(singke) #1
So, this selector says, “Find me every even table row and color it. Then find
every odd row and color that, too.” That takes care of our zebra striping
without resorting to any scripting or extra class names on rows.

With the styles applied, our table looks like this:


Now let’s work on aligning the columns in the table.


Aligning Column Text with :nth-child


By default, all of the columns in our invoice table are left-aligned. Let’s right-
align every column except for the first column. This way, our price and
quantity columns will be right-aligned and easier to read. To do the right-
alignment, we can use nth-child, but first we have to learn how it works.

The nth-child selector looks for child elements of an element and, like nth-of-type,
can use keywords or a formula.

The formula is an+b, where a is a multiple, n is a counter starting at 0, and b
is the offset. That description is not particularly helpful without some context,
so let’s look at it in the context of our table.

If we wanted to select all of the table rows, we could use this selector:


tabletr:nth-child(n)

We’re not using any multiple, nor are we using an offset.


However, if we wanted to select all rows of the table except for the first row,
which is the row containing the column headings, we would use this selector
that uses an offset:

tabletr:nth-child(n+2)

The counter is 0, but the offset is 2, which means we don’t start at the
beginning of the table; we start at the second row.

If we wanted to select every other row of our table, we’d use a multiple, or 2n.


tabletr:nth-child(2n)

Chapter 4. Styling Content and Interfaces • 72


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf