微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在CSS选择器中使用空格或大于符号>

参见英文答案 > CSS Child vs Descendant selectors7个
我有一些CSS代码
.welcome div {
   font-size: 20px;
}

这是我想要的,但也写作

.welcome > div {
   font-size: 20px;
}

会做同样的事情.

有没有理由使用一个或另外两个不同的方式做同样的事情?

解决方法

不,他们是完全不同的,使用>选择一个子元素,而使用空格将选择任何级别的嵌套元素.

例如…

在选择器中使用␣/空格…

<div class="welcome">
    <section>
        <div>This will be selected</div>
    </section>
    <div>This will be selected as well</div>
</div>

所以在这里,具有空格的选择器将在父元素的任何嵌套级别定位div.

Demo(使用␣/空格)

.welcome div {
    font-size: 20px;
    color: #f00;
}

使用>

<div class="welcome">
    <section>
        <div>This won't be selected</div>
    </section>
    <div>This will be selected</div>
</div>

在这里,选择器将定位您的div,该元素是具有.welcome的元素的子元素,但它不会选择嵌套在段标签内的div,因为它是外部div的孙(但不是子)).

Demo 2(使用>)

.welcome > div {
    font-size: 20px;
    color: #f00;
}

MDN:(对于␣)

The combinator (that’s meant to represent a space,or more
properly one or more whitespace characters) combines two selectors
such that the combined selector matches only those elements matching
the second selector for which there is an ancestor element matching
the first selector. Descendant selectors are similar to child
selectors,but they do not require that the relationship between
matched elements be strictly parent-child.

MDN :(对于>)

The > combinator separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first. By contrast,when two selectors are combined with the descendant selector,the combined selector expression matches those elements matched by the second selector for which there exists an ancestor element matched by the first selector,regardless of the number of “hops” up the DOM.

原文地址:https://www.jb51.cc/css/217370.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。