HTML and CSS Reference
In-Depth Information
would set the first <span> tag found in the paragraph to red and the last <span> tag found
to green. Of course, those might be one and the same, which would then make the item
green since that was the final rule defined and applied.
It is also possible to find particular items of a type. For example, this makes the third
<span> tag encountered in a paragraph larger,
p span:nth-of-type(3) {font-size: larger;}
while this makes the second-to-last <span> tag underlined:
p span:nth-last-of-type(2) {text-decoration: underline;}
The value of these rules as opposed to children is clear when there are other elements
found in a subtree or when you start combining rules. For example,
p#intro .fancy:nth-of-type(4n) {color: red;}
would make every fourth element in class “fancy” found within the paragraph called
“intro” red. As you see, we can get quite specific with CSS3 tree pseudo-class selectors.
If we are looking for uniqueness, we have two pseudo-classes of interest, :only-child
and :only-of-type . For example, this rule would make a span green when it is the only
child found in a paragraph:
p span:only-child {color: green;}
so
<p> I am the <span> only child so I am green </span> . </p>
<p> I have <span> two </span> <em> children </em> so no green here. </p>
If we care to look for subtrees that contain elements, only a certain type use
:only-of-type . For example,
p em:only-of-type {background-color: red;}
would set the <em> tag to have a red background if it was the only one found in a
paragraph, as demonstrated by this markup:
<p> I have a single <em> em so I am red </em> . </p>
<p> I have <em> two </em> <em> em </em> tags so neither is red. </p>
If all these different tree selectors are making your head hurt, we will finish off with
some easy ones. First is the :root pseudo-class, which in the case of (X)HTML is always
going to be the html element, so
:root {color: red;}
makes all tags red. The value of this selector is clearly for XML where the definition of the
root element in a language is variable as opposed to (X)HTML where it is always <html> .
Second is the :empty selector, which can be used to select elements that are empty (in other
words, have no children). So this rule would find all the <p> tags that are empty and show
them with a solid red border:
p:empty {border: 2px solid red;}
Search WWH ::




Custom Search