这两种风格有何不同之处:
element1 > element2 {
...
}
和
element1 element2 {
...
}
答案 0 :(得分:3)
element1 element2
选择element1
示例强>
<style>
.element1 .element2{
color: #2196F3;
background-color: #FFEB3B;
}
</style>
<div class="element1">
<p class="element2">
As you can see that this paragraph with class `element2` is inside div with class `element1` and so it's catched by css written above.
</p>
</div>
&#13;
尽管
element1 > element2
选择父级为element2
element1
<style>
.element1 > .element2{
color: #2196F3;
background-color: #FFEB3B;
}
</style>
<div class="element1">
<p class="element2">
This paragraph is catched by css above because this paragraph with class `element2` is immediate child of div with class `element1`.
</p>
</div>
<!--no effect-->
<div class="element1">
<div class="middleelement">
<p class="element2">
This paragraph is <strong>NOT</strong> catched by css written above because it's not immediate child of div with class `element1` because class `middleelement` comes in between. To refer to this paragraph, you have to write css as `.element1 > .middleelement > .element2`
</p>
</div>
</div>
&#13;
答案 1 :(得分:2)
element1 > element2
选择父级为<element2>
元素的所有<element1>
元素(有关详细信息,请参阅child combinator selector),而element1 element2
选择所有<element2>
} <element1>
元素内的元素(有关详细信息,请参阅descendant selector)。
示例:强>
如果您必须遵循DOM标记(请参阅此JSFiddle):
a
c
b
c
d
c
你使用a c {bg -> red}
(伪代码)所有c元素都将变为红色,但如果你也使用a > c {bg -> blue}
,则第一个c元素将变为蓝色,而另一个元素将变为红色。这是因为a元素是第一个c元素的直接父元素。
答案 2 :(得分:1)
>
是child combinator,表示直接的孩子,而空格(或>>
)是descendant combinator,这意味着其他元素可以位于第一个
如果您有以下DOM树
a
b
c
d
然后a > c
将不匹配,而a c
将匹配c
元素。
答案 3 :(得分:1)
element1 element2
选择elements
elements
element1 > element2
选择父级为elements
element