The difference between the child and the decendent selector [duplicate]
These appear to do the same things. I've never been sure what the difference is.
<style>
#a > b > i{
color: blue;
}
#b b i{
color: red;
}
</style>
<div id="a">
<b><i>text</i></b>
</div>
<div id="b">
<b><i>text</i></b>
</div>
There is difference.
The >
is a child selector which selects only direct/immediate elements where as #a b i
will select child elements at any depth inside the specified parent.
For your markup:
<div id="a">
<b><i>text</i></b>
</div>
<div id="b">
<b><i>text</i></b>
</div>
Both should work but still child selector is more appropriate in that situation. Consider this:
<div id="a">
<b><i>text</i></b>
</div>
<div id="b">
<b><i>text</i></b>
<b><i>text<div><span><i>text</i></span>></div></i></b>
</div>
In the above case though, the child selector will not be applied on <i>
inside the span element in <div><span><i>text</i></span>></div>
, which is not a direct child of <b>
element.
More Info:
CSS Child Selectors
Right from the specs
Child
An element A is called the child of element B if and only if B is the parent of A.
Descendant
An element A is called a descendant of an element B, if either (1) A is a child of B, or (2) A is the child of some element C that is a descendant of B.
精彩评论