儿童和后代组合选择器之间的区别 [英] Difference between Child and Descendant Combinator Selectors

查看:114
本文介绍了儿童和后代组合选择器之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用子组合器选择器进行练习,但结果似乎有些不尽相同.

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

我设置了以下示例html:

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.

这是怎么回事?

下面是一个我希望它如何表现的示例.

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

示例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>

并使用此选择器:

ul.Parent > li {
color: blue;
}

第二个示例仅选择孩子,就像我期望的那样.但是,当使用嵌套的divs时,它总是沿着链条到达大孩子.

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?

推荐答案

在您的第一个示例中,只有一个.One元素和只有一个.Two元素,并且.Two是该.因此,无论您使用子组合还是子组合都不会有任何不同-两个选择器都将仅匹配该单独的.Two元素.任何E > F对都必然也是E F对;前者是后者的适当子集.

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:

  • 如果要比较子组合器和后代组合器,请避免使用color-正如其他人提到的那样,它是继承的,这会使您感到困惑. (这适用于两个示例.)

  • 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.)

内部ol实际上没有继承它的唯一原因是因为您没有正确地将其嵌套在外部li元素之一中.

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.

但是,它仍然说明了子组合器为何如广告所述那样工作:因为内部的li元素不是外部的ul的子元素.它们是内部ol的子代.

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.

这篇关于儿童和后代组合选择器之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆