Reputation:
What is the difference between these two CSS statements:
h1 em { color:#ddd; }
and
h1 > em { color:#ddd; }
As far as I can tell they do exactly the same thing (though according to what I've read at W3C in the first case em is considered a 'descendant' where as in the second it is considered a 'child', though I have no idea how that is actually different). Can anyone explain how these are different and why you would choose to use one syntax over the other. I've always just used the first method, but every now and again I run across the second style in other people's code.
Upvotes: 3
Views: 1260
Reputation: 281605
This one:
h1 em { color:#ddd; }
matches any em
that's within an h1
, whether it's a child, grandchild, great-grandchild, etc. For instance:
<h1><strong><em>This matches</em></strong></h1>
This one:
h1 > em { color:#ddd; }
matches only an em
that's a child of an h1
, not a grandchild, great-grandchild, etc. So:
<h1><strong><em>This doesn't match</em></strong></h1>
<h1><em>But this does</em></h1>
Upvotes: 17
Reputation: 2340
The child selector in this the > symbol lets you select only those em tags that are direct descendants of an h1 tag.
Example is the easiest way to explain it:
<h1>H1 Tag <em id="first">child selector<em id="second">not a direct child descendant</em></em> </h1>
In this case the first em tag will have the h1 > em style and the h1 em style applied, however the second em tag or the non direct child will not have h1 > em style applied since it is not a direct child or descendant of the h1.
You can see the doctree spec here: http://www.w3.org/TR/CSS2/conform.html#doctree
Upvotes: 0
Reputation: 6429
Just fyi, there are still a lot of browser compatibility issues with using > and it is a case where I would use jQuery or at least test in all your target browsers before deploying.
Upvotes: 0
Reputation: 30160
A descendant is any element that appears below the containing element at any point in the DOM tree (a child, grand-child type relationship). A child is an element that is directly below the containing element in the DOM.
The real world implications in using this are that the child selector, alongside the sibling selector, are not support by IE6.
Upvotes: 0
Reputation: 23289
h1 em { color:#ddd; }
means: "em within h1"
h1 > em { color:#ddd; }
means: "em with parent h1"
Upvotes: 0
Reputation: 6955
Probably not the best example that you've given but I'll run with it:
<h1>Stuff here
<em>Something
<p>More stuff</p>
<p>Something <em>here</em></p>
</em>
<h1>
h1 em will match both em in my example.
h1>em will only match the em that is a direct descendant of the h1 not the second inner em.
Upvotes: 2