Difference between Child and Descendant Combinator Selectors

匆匆过客 提交于 2019-12-11 12:44:22

问题


I've been trying to practice using the child combinator selector and seem to be having some mixed results.

I set up the following sample html:

<div class="One">
    One Text
    <div class="Two">
        Two Text
        <div class="Three">
            Three Text
            <div class="Four">
                 THE BASE IS HERE.  
            </div>
        </div>
    </div>
</div>

Then I tried to do the following.

div.One > div.Two {
    color: blue;
}

My results were the same as if I had just used a descendant selector. Although, when I tried using the child combinator with ordered list inside of a unordered list, it seemed to work just as I would expect.

What's going on here?

Below is an example of how I would expect it to behave.

Sample HTML:

<ul class="Parent">
<li>One</li>
<li>Two</li>
    <ol class="Child">
        <li>One One</li>
        <li>Two Two</li>
    </ol>
<li>Three</li>

and using this selector:

ul.Parent > li {
color: blue;
}

This second example ONLY selects the child as I would expect it to behave. But when using the nested divs... it goes always down the chain to the grand children.

So my question is, why does it only select the child in the second example and not in the first?


回答1:


In your first example, there is only one .One element and only one .Two element, and that .Two is a child of that .One. So whether you use the child or descendant combinator isn't going to make any difference — both selectors are going to match just that lone .Two element. Any E > F pair is necessarily also an E F pair; the former is a proper subset of the latter.

Your second example is flawed for two reasons:

  • If you want to compare the child and descendant combinators, avoid using color — as others have mentioned it's inherited which can confuse you. (This applies to both examples.)

  • The only reason it's not actually being inherited by the inner ol is because you're not correctly nesting it within one of the outer li elements.

However, it nevertheless demonstrates why the child combinator works as advertised: because the inner li elements are not children of the outer ul. They are children of the inner ol.




回答2:


The child combinator selector (>) targets an element that is a child of its parent. It does not target descendants beyond the children.

The descendant selector targets the child and other descendants of the parent/ancestor.

Both selectors target child-level elements, so in those cases there won't appear to be any difference between them.

See a list of selectors with definitions here: http://www.w3.org/TR/css3-selectors/#selectors



来源:https://stackoverflow.com/questions/33442967/difference-between-child-and-descendant-combinator-selectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!