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

2022-01-10 00:00:00 css-selectors css

我有一些 CSS 代码:

I have some CSS code:

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

它做我想做的事,但也写得像

which does what I want it to do, but also writing it like

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

也会这样做.

是否有任何理由使用一种而不是另一种,或者它们只是做同一件事的两种不同方式?

Is there any reason to use one over the other or are they just two different ways of doing the same thing?

推荐答案

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

No they are completely different, using > selects a child element whereas using a space will select a nested element at any level.

例如……

在选择器中使用 /space…

Using /space in the selector…

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

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

So here, the selector having space will target the div at any nested level of the parent element.

演示 (使用<代码>␣/空格)

.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 的元素的 child,但它不会选择div 嵌套在 section 标记内,因为它是外部 div 的孙子(但不是子).

Whereas here, the selector will target your div which is a child of the element having .welcome but it won't select the div which is nested inside section tag as it is a grandchild (but not a child) of the outer div.

演示 2 (使用 >)

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

<小时>

来自 MDN :(对于 )

组合子(用于表示空格或更多一个或多个空白字符)组合了两个选择器这样组合的选择器只匹配那些匹配的元素有祖先元素匹配的第二个选择器第一个选择器.后代选择器类似于 child选择器,但它们并不要求它们之间的关系匹配的元素是严格的父子元素.

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 : (对于 >)

From MDN : (For >)

> 组合器分隔两个选择器并只匹配那些由第二个选择器匹配的直接子元素第一个匹配的元素.相比之下,当两个选择器结合后代选择器,组合选择器表达式匹配由第二个选择器匹配的那些元素存在与第一个选择器匹配的祖先元素,与 DOM 上的跃点"数无关.

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.

相关文章