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:


<html>
<body>
<table>
<caption>Yearly Income 2006-2010</caption>
</body>
<tr>
<th></th>
<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>
</tr>
<tr>
<th scope="row">Grants</th>
<td>11,980</td>
<td>12,650</td>
<td>9,710</td>
<td>8,980</td>
<td>11,420</td>
</tr>
<tr>
<th scope="row">Donations</th>
<td>1,430</td>
<td>2,280</td>
<td>3,702</td>
<td>3,4510</td>
<td>2,409</td>
</tr>
<tr>
<th scope="row">Investments</th>
<td>14,988</td>
<td>12,320</td>
<td>10,970</td>
<td>8,990</td>
<td>10,820</td>
</tr>
<tr>
<th scope="row">Fundraising</th>
<td>22,150</td>
<td>18,650</td>
<td>19,840</td>
<td>18,369</td>
<td>21,494</td>
</tr>
<tr>
<th scope="row">Sales</th>
<td>21,000</td>
<td>22,550</td>
<td>29,000</td>
<td>28,150</td>
<td>31,400</td>
</tr>
<tr>
<th scope="row">Miscellaneous</th>
<td>1,980</td>
<td>1,560</td>
<td>971</td>
<td>898</td>
<td>780</td>
</tr>
</html>

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 */

</style>

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 

<tr>
<th scope="row">Endowments</th>
<td>2,150</td>
<td>8,650</td>
<td>1,984</td>
<td>1,869</td>
<td>2,149</td>
</tr>

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?



ċ
sampletablecode.html
(1k)
Peter Knowles,
Dec 14, 2011, 12:20 PM
Comments