Advanced Contextual Selectors


The context of an element consists of all the element's ancestors and all elements that precede it in the document. It is not possible to look at elements that follow an element because browsers often need to be able to decide on the style of an element before the rest of the document comes in. The most common contextual selector is the one that was explained earlier, in the section, "Simple contextual selectors." It only checks whether an element is inside some other element, without regard for how far removed that ancestor is.

Two other contextual selectors, the child selector and the sibling selector, give precise control over the relation between the element to select and its context. In combination with the first-child pseudo-class explained next, these can be used to trace out a path from some element to the element you want to select.

The Child Selector

To select an element under the condition that its parent matches some other selector, you can use a rule like the following:

 DIV.chapter DIV.warning > P { text-indent: 0 } 

This rule selects any P elements whose parent matches DIV.CHAPTER DIV.WARNING; in other words, all P elements that are children of a DIV element with class warning that is inside a DIV element of class "chapter." This may be quite different from the following:

 DIV.chapter > DIV.warning P { text-indent: 0 } 

The Sibling Selector

Sometimes what determines the style of an element is not so much its parent or other ancestors, but the element that precedes it. A typical example is the indentation of the first line of a paragraph. This book uses that device to make it easier to spot where one paragraph ends and the next one begins.

The rule is that an indent is only used between paragraphs; in other words, not on a paragraph that follows a heading, a list, or something else that is already visually distinguished. Expressed in CSS, the rule becomes

 P + P { text-indent: 2em } 

This matches a P if it is preceded by another P, and both have the same parent.

Here is a triplet of rules that sets the font size of H1 and H2 elements: By themselves, they are set to fairly large letters, but when an H2 immediately follows an H1, it is made smaller. You might do this, for example, because such H2 function as subtitles:

 H1 { font-size: xx-large } H2 { font-size: x-large } H1 + H2 { font-size: medium } 



Cascading Style Sheets(c) Designing for the Web
Cascading Style Sheets: Designing for the Web (3rd Edition)
ISBN: 0321193121
EAN: 2147483647
Year: 2003
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net