CSS Basics: What does ">" in a selector mean?
Matching children versus matching all descendants
>
is the child selector. Given this tag structure:
<div class="foo">
<div>
<p>A grand-child of div.foo</p>
</div>
<p>A child of div.foo</p>
</div>
div.foo p
matches both <p>
elements, because it selects all <p>
that are descendants of <div class="foo">
. No matter how many levels deep, if there's a <p>
tag inside <div class="foo">
, div.foo p
will match it.
But div.foo>p
(or div.foo > p
) matches only the second <p>
element, because it selects only those <p>
that are direct children of <div class="foo">
with no other nesting tags in between.
Why use the child selector
The child selector makes some things very easy that are a pain to do with only descendent selectors. E.g., styling the first level of a <ul>
differently from the second or third level.
It used to be the case that child selectors were much faster for browsers to match than descendant selectors, but browsers got smarter so that's not much of a concern anymore.
In writing CSS, I prefer to use the child selector when possible. Stylesheets can get so big that it's difficult to remember what all you have in them, and using the child selector when appropriate instead of the descendant selector means fewer rules that may apply all over my document, even once I've forgotten about them.
Why not use the child selector
If you need to support Internet Explorer 6, or Internet Explorer 7 or 8 in quirks mode, you can't use the child selector—and may God have mercy on you.
Internet Explorer 6 is pretty ancient history by now, but it's still the reason you've managed to write CSS until today without learning what >
means in a selector. Stylesheet authors years ago couldn't reliably use it, so examples in the wild are still relatively few.