CSS, How To use advanced selectors.

Thursday, 6. August 2009

Child selectors

Child selectors are used to selected an element that is a direct child of another elements parent. Child selectors will not selected 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>

*Child selectors are not supported by IE 5, 5.5 or 6, but are supported by most other browsers.

div > em {
color: blue;
}

Adjacent sibling selectors

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 immediatly follow an <h2> element. This is a commonly used example because it has a real-world application. There is often to much space between <h2> and <h3> elements when they appear immediately after each other.

*Adjacent selectors are not supported by IE 5, 5.5 or 6, but are supported by most other browsers.

h2 + h3 {
margin: -1em;
}

Attribute selectors

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”

*Attribute selectors are not supported by IE 5, 5.5 or 6, but are supported by most other browsers.

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

Pseudo-elements

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

*Pseudo-elements selectors are not supported by IE 5, 5.5 or 6, but are supported by most other browsers.

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

Pseudo-classes

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 will be covered in later posts.