Class selectors are custom selectors that you give a name to; you precede that name with a dot, as in .classname
. Classes are then applied to an element in the HTML using the class
attribute, with a value of the class name:
<tr class="classname"> . . . </tr>
Typically, you'll want to describe the function of the class rather than the presentation. So, if you're going to apply a background color to every other table row, you'll want to name your class something like .alternaterow
instead of .gray
. This way, if you want to change the color, you needn't change the class name throughout your documents, which defeats the management advantages of CSS.
Example 8.4 shows a modified table you first worked with in tutorial 4, "Creating Tables." You'll note that I made one change in the table markup: I took out all the table attributes except for cellspacing
. This is because there is no effective means of providing cellspacing
in CSS.
I've also added an embedded style sheet that includes the table width
, border
, and padding
styles, along with element selectors and a class selector to style the table using background colors in the elements.
Example 8-4. Styling the table with element and class selectors
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>working with style</title> <style type="text/css"> body {color: white;} caption {background-color: #999; border: 1px solid black;} table {background-color: #ccc; border: 1px solid black; padding: 5px; width: 90%;} th {background-color: #333; border:} tr {background-color: #999;} td {background-color: #ccc; border: 1px solid black;} .highlight {background-color: #fff; color: orange;} </style> </head> <body> <table cellspacing="5"> <caption>Comparing weather and time zones</caption> <tr> <th>Location</th> <th>Tucson, Arizona</th> <th>Las Vegas, Nevada</th> </tr> <tr> <th>Weather</th> <td>Warm to Hot</td> <td>Warm to Hot</td> </tr> <tr> <th>Time Zone</th> <td>No Daylight Savings</td> <td class="highlight">Mountain Standard Time</td> </tr> </table> </body> </html>
Figure 8-5 shows the results.
Figure 8-5. Styling a table with element and class selectors.
NOTE
You'll also notice I added borders to spice things up a bit. You can learn more about styling borders in tutorial 11, "Margins, Borders, and Padding."
As you are beginning to find out, you can do a lot with CSS to enhance your documents. Here we've turned a plain-vanilla table into something with a little style.