CSS选择器差异

时间:2015-02-19 14:52:40

标签: html css css-selectors

这个问题可能已经问过并回答了一百万次,但我只是想知道使用.div1 > .div1-1.div1 .div1-1进行比较的区别。

我知道">"是子选择器所以.div1 (parent) > .div1-1 (child)

<div class="div1">
<div class="div1-1">Test</div>
</div>

.div1 > .div1-1{ color:red;}

哪种方法最好使用?

1 个答案:

答案 0 :(得分:1)

尝试:

<style>
    .div1 .div1-1 {color: red;} /* all children */
    .div1 > .div1-1 {background: blue;} /* direct children */
</style>

<div class="div1">
    <div class="div1-1">Test</div>
</div>

// both .div1 > .div1-1 and .div1 .div1-1 do the same
// both rules are applied

http://jsfiddle.net/yb1Lfsd8/

VS

<style>
    .div1 .div1-1 {color: red;} 
    .div1 > .div1-1 {background: blue;}
</style>

<div class="div1">
    <div>
        <div class="div1-1">Test</div>
    </div>
</div>

// Just .div1 .div1-1 change styles to '.div1-1'
// The first rule is applied only

http://jsfiddle.net/yb1Lfsd8/1/