• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Lesson 3. Selectors in Action > Advanced Selectors

Advanced Selectors

Child selectors are used to select an element that is a direct child of another element (parent). Child selectors will not select all descendants, only direct children. For example, you might want to target an <em> that is a direct child of a <div>, but not other <em> elements that are descendants of the <div>. The selector is shown in Listing 3.11.

Child selectors are not supported by Windows Internet Explorer 5, 5.5, and 6, but are supported by most other standards-compliant browsers.

Listing 3.11. CSS Code Containing the Child Selector

div > em
{
     color: blue;
}

Adjacent sibling selectors will select the sibling immediately following an element. For example, you might want to target an <h3> element, but only <h3> elements that immediately follow an <h2> element. This is a commonly used example because it has a real-world application. There is often too much space between <h2> and <h3> elements when they appear immediately after each other. The selector is shown in Listing 3.12.

Adjacent sibling selectors are not supported by Windows Internet Explorer 5, 5.5, and 6, but are supported by most other standardscompliant browsers.

Listing 3.12. CSS Code Containing the Adjacent Sibling Selector

h2 + h3
{
    margin: -1em;
}

Attribute selectors are used to select elements based on their attributes or attribute value. For example, you might want to select any image on an HTML page that is called "small.gif" as shown in Listing 3.13.

Attribute selectors are not supported by Windows Internet Explorer 5, 5.5, and 6, or Macintosh Internet Explorer 5. They are also not supported by earlier versions of Opera.

Listing 3.13. CSS Code Containing the Attribute Selector

img[src="small.gif"]
{
    border: 1px solid #000;
}

Pseudo-elements enable you to style information that is not available in the document tree. For instance, using standard selectors, there is no way to style the first letter or first line of an element’s content. However, the content can be styled using pseudo-elements as shown in Listing 3.14.

Pseudo-elements :before and :after are not supported by Windows Internet Explorer 5, 5.5, and 6, or Macintosh Internet Explorer 5. They are also not supported by earlier versions of Opera.

Listing 3.14. CSS Code Containing the Psuedo-Element Selector

p:first-line
{
    font-weight: bold;
}

p:first-letter
{
    font-size: 200%; font-weight: bold;}

Pseudo-classes enable you to format items that are not in the document tree. They include :first-child, :link, :visited, :hover, :active, :focus, and :lang(n). Pseudo-classes are covered in Lesson 10, “Styling Links.”

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint