Skip to main content

Use Cascading Style Sheets selectors

Harness the power of CSS by choosing just the content you want

Nicholas Chase (nicholas@nicholaschase.com), President, Chase and Chase, Inc.
Nicholas Chase has been involved in Web site development for companies such as Lucent Technologies, Sun Microsystems, Oracle, and the Tampa Bay Buccaneers. Nick has been a high school physics teacher, a low-level radioactive waste facility manager, an online science fiction magazine editor, a multimedia engineer, and an Oracle instructor. More recently, he was the Chief Technology Officer of Site Dynamics Interactive Communications in Clearwater, Florida, and is the author of three books on Web development, including Java and XML From Scratch (Que). He loves to hear from readers and can be reached at nicholas@nicholaschase.com.

Summary:  With Cascading Style Sheets (CSS), page authors can control the appearance of content with more precision. CSS rules consist of a selector that determines the content to which the rule applies, and the properties and values that are set. While most developers are accustomed to using selectors that are based on tag names, CSS actually provides several different options that enable even greater control. This article discusses each type of selector and shows you how to use it.

Date:  01 Sep 2002
Level:  Intermediate
Activity:  227 views
Comments:  

Note:This article shows the use of CSS selectors in browsers such as Microsoft Internet Explorer 6.0 and Netscape 7, but basic selectors are available as far back as Netscape Navigator 4.x and Internet Explorer 4.x. A basic understanding of Cascading Style Sheets is helpful.


The basic page and the universal selector

To demonstrate the use of different CSS selectors, I use in this article the results of a dog show. I've specifically constructed the page to provide the different examples needed, but otherwise it's a perfectly normal page, as shown in Figure 1 and Listing 1.


Figure 1. The basic page
The basic Page

Listing 1. The basic page
		
<html>
<head>
   <title>New Port Richey</title>
</head>
<body>
<h2 align="center">The New Port Richey Dog Show</h2>
<h4 align="center">Show Date: 7/31/2001</h4>
<h4 align="center">New Port Richey, FL</h4>

<p align="center">
   <span class="category">Best In Show:</span> 
   <span id="bestinshow">CH Sarah's Razzle Dazzle
   (Yorkshire Terrier)</span>
</p>

<p><a href="complete">Complete results</a></p>

<table align="center">
<tr>
   <td class="category">
       <a href="herding.html">Herding Group:</a>
   </td>
   <td>German Shepherd Dog</td>
   <td>CH Sabre Dawn</td>
</tr>
<tr>
   <td class="category">
      <a href="toy.html">Toy Group:</a>
   </td>
   <td>Yorkshire Terrier</td>
   <td>CH Sarah's Razzle Dazzle</td>
</tr>
<tr>
   <td class="category">
      <a href="sporting.html">Sporting Group:</a>
   </td>
   <td>Golden Retriever</td>
   <td>CH Chase's Golden Chance</td>
</tr>
<tr>
   <td class="category">
      <a href="nonsporting.html">Non-Sporting Group:</a>
   </td>
   <td>Tibetan Terrier</td>
   <td>CH Winston of Sunny Brook Lane</td>
</tr>
</table> 
</body>
</html>

To start with, create the style element into which the various CSS rules will be placed. The simplest possible style sheet is one that applies a particular rule to all content within the page. Creating such a rule involves creating a style element and a rule using the universal selector, * (See Listing 2):


Listing 2. The universal selector
		
<html>
<head>
   <title>New Port Richey</title>
   <style type="text/css">
      * { font-family: Verdana }
   </style>
</head>
<body>
<h2 align="center">The New Port Richey Dog Show</h2>
<h4 align="center">Show Date: 7/31/2001</h4>
...

While this selector doesn't work in Netscape 4.x browsers, in other cases it applies the style to all appropriate content. The example in Listing 2 applies a font change, as shown in Figure 2. (Some style properties, of course, don't make sense for certain elements. You wouldn't set a font change on a graphic, for example.)


Figure 2. The universal selector applies a style to all appropriate content.
The universal selector

Type selectors

Perhaps the most commonly used selector is the type selector, though most people think of it as a tag name or element selector. This selector chooses content based on the name of the element. For example, the following code in Listing 3 changes the size of any text within a table data (td) element, as shown in Figure 3:


Listing 3. Type selectors
		
...
   <style type="text/css">
      * { font-family: Verdana }
      td { font-size: 10pt }
   </style>
...

This style applies to any text within a table data element, no matter where it is in the hierarchy of the page.


Figure 3. Using a type selector
Type selectors

Class selectors

After type selectors, the most commonly used selectors are class selectors. A class selector selects all elements that have a class attribute with a particular value. Preceding the name of the class with a period (.) signals to the browser that this is a class selector. For example, the following code in Listing 4 bolds any text that is in the category class:


Listing 4. Using a class selector
		
   <style type="text/css">
      * { font-family: Verdana }
      td { font-size: 10pt }
      .category { font-weight: bold; }
   </style>
...

Classes are an excellent way to increase the maintainability of Web pages, because wholesale changes can be made to the look and feel of a site with just a change to the stylesheet. Classes make it possible to discriminate based on logical or business criteria, rather than simply by an accident of layout. For example, you might create a class that allows you to set all person names to a particular style.

In some cases, you might find it useful to further restrict a class-based rule based on the element to which the class is attached. You can accomplish this task by appending the class name to the element name. For example, category names within a table data cell can be set to italics as shown in Listing 5.


Listing 5. Restricting a class based on element
		
...
   <style type="text/css">
      * { font-family: Verdana }
      td { font-size: 10pt }
      .category { font-weight: bold; }
      td.category { font-style: italic }
   </style>
...

Because the text "Best In Show" is outside a table data element, the new rule doesn't apply, as shown in Figure 4.


Figure 4. Using class selectors
class selectors

ID selectors

Another specialty selector is the ID selector. Like the class, an ID selector is based on the value of an attribute, but in this case, it's the ID attribute. This selector is used to single out a particular element; IDs should be unique within a document. For example the following code in Listing 6 selects the span designated as bestinshow by preceding the name with a pound sign (#) and colors it red, as shown in Figure 5.


Listing 6. Using the ID selector
		
...
   <style type="text/css">
      * { font-family: Verdana }
      td { font-size: 10pt }
      .category { font-weight: bold; }
      td.category { font-style: italic }
      #bestinshow { color: red }
   </style>
...


Figure 5. The ID selector selects a specific element
id selectors

Family relationships: descendants, children, and siblings

CSS enables the application of rules based not only on an element's name, but also on its position within the overall document. For example, a rule might select links, but only if they are within a paragraph tag. In the Document Object Model, this is known as being a descendant of the paragraph element, which is the ancestor. In this case, the selector is the ancestor element name followed by the descendant element name. For example, the following code in Listing 7 removes the underline for any links that are part of a paragraph (as opposed to those within the table) as shown in Figure 6.


Listing 7. Using the ID selector
		
...
   <style type="text/css">
      * { font-family: Verdana }
      td { font-size: 10pt }
      .category { font-weight: bold; }
      td.category { font-style: italic }
      #bestinshow { color: red }
      p a { text-decoration: none }
   </style>
...

Note that this rule applies to a link anywhere within a paragraph, even if it's nested within another element. For example, if the HTML were actually:

<p><b><a href="complete">Complete results</a></b></p>

the link would still be a descendant of the paragraph element.

It is possible, however, to limit the selector to only the direct (first generation, so to speak) child of the ancestor, or parent. The child selector, which at the time of this writing is only supported by Netscape 6 and above, restricts a rule to immediate children of the parent element. The child selector uses the greater-than sign, like this:

p > a { text-decoration: none }

Another newer selector that hasn't made its way to Internet Explorer yet is the following sibling selector, which uses a plus sign (+). In this case, a rule applies only to elements that immediately follow another particular element. For example, the following code in Listing 8 italicizes only an h4 element that follows another h4 element, so the first h4 element remains unchanged, as shown in Figure 6.


Listing 8. Using the following-sibling selector
		
...
   <style type="text/css">
      * { font-family: Verdana }
      td { font-size: 10pt }
      .category { font-weight: bold; }
      td.category { font-style: italic }
      #bestinshow { color: red }
      p a { text-decoration: none }
      h4 + h4 { font-style: italic }
   </style>
...


Figure 6. Descendant, child, and following-sibling selectors
descendant selectors

Pseudo-classes and pseudo-elements

Finally, let's look at a group of selectors that is not based on any particular element but on specific conditions within the document: pseudo-classes. Designated by a colon preceding the name, pseudo-classes are independent of particular elements and instead look at what's happening within the document. The most common (and most widely implemented, though not available in Netscape 4.x) is the :hover pseudo-class, which applies when the user rolls the mouse over an element, as shown in the code in Listing 9 and in Figure 7.


Listing 9. Using the :hover pseudo-class
		

...
   <style type="text/css">
      * { font-family: Verdana }
      td { font-size: 10pt }
      .category { font-weight: bold; }
      td.category { font-style: italic }
      #bestinshow { color: red }
      p a { text-decoration: none }
      h4 + h4 { font-style: italic }
      :hover { background-color: red }
   </style>
...


Figure 7. Using the :hover pseudo-class
hover pseudo class

Other, less-widely supported pseudo-classes include :first-child, :link, :visited, :active, and :focus and :lang. Note that a pseudo-class can be applied to a specific element type, like this:

p:first-child { font-size: larger }

Pseudo-elements are similar to pseudo-classes (and share syntax with them) but define content within the document. Pseudo-elements defined by the CSS2 Recommendation include:

  • :first-line, which selects the first line of content, even if that changes based on the size of the window
  • :first-letter, which can be used for effects such as drop caps
  • :before and :after, which are combined with another selector and are usually used to insert content into the document, like this:
    • *.category:before { content: "Category: " }

Summary

This article looked at the different types of selectors available within the CSS2 Recommendation. Browser support for some is limited, but CSS is designed for graceful degradation; a page should still be legible and usable if a style isn't applied. However, you should always test pages in all target browsers.


Resources

About the author

Nicholas Chase has been involved in Web site development for companies such as Lucent Technologies, Sun Microsystems, Oracle, and the Tampa Bay Buccaneers. Nick has been a high school physics teacher, a low-level radioactive waste facility manager, an online science fiction magazine editor, a multimedia engineer, and an Oracle instructor. More recently, he was the Chief Technology Officer of Site Dynamics Interactive Communications in Clearwater, Florida, and is the author of three books on Web development, including Java and XML From Scratch (Que). He loves to hear from readers and can be reached at nicholas@nicholaschase.com.

Comments



Trademarks

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development
ArticleID=11699
ArticleTitle=Use Cascading Style Sheets selectors
publish-date=09012002
author1-email=nicholas@nicholaschase.com
author1-email-cc=