問題描述
我有一些 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.
這篇關于使用空格或大于號 >在 CSS 選擇器中?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!