Today I'll look at two aspects of CSS that are directly related to the “family tree” that we discussed in regards to descendant selectors: the child and sibling selectors.
The Ranged Child Selector
The child selector is relatively common in production, although I must confess I do not employ it as much as I should. Very simply, it selects only elements that are direct children of a particular element. As an example, take an HTML5 <article>
element with some paragraphs, and a <footer>
element that contains more paragraphs inside that:
<article>
<p>A wandering minstrel I…
<p>A thing of shreds and patches…
<p>Of ballads, songs and snatches…
<footer>
<p>And dreamy lullaby!
</footer>
</article>
Let’s apply a standard descendant selector:
article p {
font-weight: bolder;
text-indent: 2em;
}
The result is that every paragraph inside the article is rendered stronger:
A wandering minstrel I…
A thing of shreds and patches…
Of ballads, songs and snatches…
And dreamy lullaby!
Contrast this with a child selector:
article > p {
font-weight: bolder;
text-indent: 2em;
}
The result is now:
A wandering minstrel I…
A thing of shreds and patches…
Of ballads, songs and snatches…
And dreamy lullaby!
As you can see, the child selector is ranged: rather than changing the appearance of every paragraph, it only affects those that are immediate children of the <article>
, and entirely avoids the paragraph inside the <footer>
.
Employed logically, child selectors can be lifesavers: all too often developers find themselves undoing changes created by out-of-control CSS. For example, if we started our CSS above with a descendant selector, we’d have to write at least one more declaration to reverse the effect of inheritance on the footer:
article p {
font-weight: bolder;
text-indent: 2em;
}
article footer p {
font-style: normal;
text-indent: -2em;
}
Using child selectors in development does require some pre-planning – “I want this effect to start here and not work its way lower than this” – but using them can save a great deal of work down the line.
Photograph by Brian Auer, under a Creative Commons Attribution-NonCommercial-NoDerivs 2.0 license
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.