开发者

The difference between the child and the decendent selector [duplicate]

开发者 https://www.devze.com 2023-01-07 04:47 出处:网络
This question already has answers here: 开发者_如何转开发 CSS Child vs Descendant selectors (8 answers)
This question already has answers here: 开发者_如何转开发 CSS Child vs Descendant selectors (8 answers) Closed 8 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消