HTML and CSS Reference
In-Depth Information
Selecting empty elements
With the pseudo-class :empty , you can select any element that has no children of any
kind, including text nodes, which covers both text and whitespace. This can be useful
in suppressing elements that a CMS has generated without filling in any actual content.
Thus, p:empty {display: none;} would prevent the display of any empty paragraphs.
Note that in order to be matched, an element must be, from a parsing perspective, truly
empty—no whitespace, visible content, or descendant elements. Of the following ele-
ments, only the first and last would be matched by p:empty .
<p> </p>
<p><!—-a comment--></p>
The second and third paragraphs are not matched by :empty because they are not
empty: they contain, respectively, a single space and a single newline character. Both
are considered text nodes, and thus prevent a state of emptiness. The last paragraph
matches because comments are not considered content, not even whitespace. But put
even one space or newline to either side of that comment, and p:empty would fail to
You might be tempted to just style all empty elements with something like *:empty
{display: none;} , but there's a hidden catch: :empty matches HTML's empty elements,
like img and input . It could even match textarea , unless of course you insert some
default text into the textarea element. Thus, in terms of matching elements, img and
img:empty are effectively the same. (They are different in terms of specificity, which
we'll cover in just a bit.)
As of early 2012, :empty is unique in that it's the only CSS selector that
takes text nodes into consideration when determining matches. Every
other selector type in Selectors Level 3 considers only elements and ig-
nores text nodes entirely—recall, for example, the sibling combinators
discussed previously.
Selecting unique children
If you've ever wanted to select all the images that are wrapped by a hyperlink element,
the :only-child pseudo-class is for you. It selects elements when they are the only child
element of another element. So let's say you want to remove the border from any image
that's the only child of another element. You'd write:
img:only-child {border: 0;}
This would match any image that meets those criteria, of course. Therefore, if you had
a paragraph which contained an image and no other child elements, the image would
be selected regardless of all the text surrounding it. If what you're really after is images
Search WWH ::

Custom Search