CSS直接后代(>)在选择性上没有任何价值吗?

ouc*_*cil 8 css html5 css-selectors css3

给出以下类声明和代码......

.foo > a { color:green; }
.bar a { color:red; }
Run Code Online (Sandbox Code Playgroud)
<div class="bar">
    <div class="foo">
        <a href="#">SOME LINK</a>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

...我认为链接是绿色的,因为虽然两个声明都有一个类(010)和一个元素(001),但它.foo有直接的后代选择器.但唉,这个链接是红色的. 为什么?

Bho*_*yar 10

>css特异性没有价值.

两种情况都有11个特异性值:

.foo > a { color:green; }/*specificity value is 11*/
.bar a { color:red; }/*specificity value is 11*/
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您可以使用这样的更具体的特点:

.bar .foo > a { color:green; }/*greater specificity value is 21*/
.foo a { color:red; }/*specificity value is 11*/
Run Code Online (Sandbox Code Playgroud)

好的,我要在这里添加特异性如何工作:

Selector                          Specificity         Specificity in large base
inline-style                      1 0 0 0             1000
id selector                       0 1 0 0              100
class,pseudo,attribute selector   0 0 1 0               10
type selector and pseudo elements 0 0 0 1                1                     
Run Code Online (Sandbox Code Playgroud)

  • 它不在基数 10 中。它在一个任意大的基数中。例如,11 个类型选择器(或任意数量的)仍然比 1 个类选择器具有更少的特异性。 (2认同)
  • @oucil:好问题.这是因为儿童组合子和后代组合子是相同的.儿童组合子也可以称为直接后裔组合子.儿童组合子只是一种后代组合子.例如,对于`<p> <span> a </ span> <span> b </ span> </ p>` - `p span`与`p> span`相同.因此,优先考虑是冲突的.此外,如果有嵌套元素,即使这样,孩子也是后代.因此CSS规范没有组合优先级的概念,并且在这种情况下依赖于顺序. (2认同)