December 14

posted Dec 14, 2011, 12:20 PM by Peter Knowles
So now that you've seen what pseudo-class selectors can do, you've played around with them a bit, now it's time to see how a few of the more complicated ones might be useful.

Remember awhile ago when you made a fancy table with different lines colored differently? Your might have looked like this:

<caption>Yearly Income 2006-2010</caption>
<th scope="col">2006</th>
<th scope="col">2007</th>
<th scope="col">2008</th>
<th scope="col">2009</th>
<th scope="col">2010</th>
<th scope="row">Grants</th>
<th scope="row">Donations</th>
<th scope="row">Investments</th>
<th scope="row">Fundraising</th>
<th scope="row">Sales</th>
<th scope="row">Miscellaneous</th>

To make the alternating rows change colors (and do everything else) you had to name every other row by a different class name (tr class="row" and tr class="altrow", for example) then provide a different CSS code for each class. 

That was a lot of work. And then what if you needed to add another row, right in the middle of the table. You'd have to rename each row. Even more work. 

But one pseudo-class style allows you to skip all that work, in the beginning, and when you want to add a new row.

Here's how:

In the CSS codespace of your page, create the following pseudo-class code:

<style type="text/css">

tr:nth-child(2n) { background-color: #cccccc; } /* even numbered rows are gray */
tr:nth-child(2n+1) { background-color: #e7ecf1; } /* odd numbered rows are blue */


This will give each row of your table an alternating color. 

You can expand the styling code to do some of the other things you've done before (change the font color, change the font-family or weight or style. Anything. Try it out)

After you've successfully coded your table using this CSS style, it's time to add a row to your table. 

Add a new row 

<th scope="row">Endowments</th>

after the row titled "Grants".

In the old coding approach, you'd now have to rename all the rows to make the color switch continue. 

In this approach, it shouldn't require ANY changes in the HTML (except adding the new row, of course).

Were you able to accomplish this? 

Where else might such a CSS style be helpful?

Peter Knowles,
Dec 14, 2011, 12:20 PM