CSS: Child selector higher precedence than class selecctor?

微笑、不失礼 提交于 2020-01-12 18:47:18

问题


I have the following HTML:

<div class="form-square">
     <div class="seven-col">
        Hello World!
      </div>
</div>

And the following CSS:

div.form-square > div {
    padding: 50px;
}

.seven-col {
    padding: 0;
}

Firefox and Firebug is using the first of the two CSS rules. How come "div.form-square > div" has higher precedence than ".seven-col" which is more specific?


回答1:


div.form-square > div consists of 1 class selector + 2 type selectors (plus a child combinator).

.seven-col consists of 1 class selector.

The number of class selectors is equal, so the comparison is done in type selectors. The first selector has more type selectors so it is more specific.

Specificity is based on the number of each kind of selector in the entire thing, not for the part on the right hand side of the rightmost combinator.

(NB: The first example also has what CSS 2 calls a child selector, but that doesn't count towards specificity and describes a relationship between elements rather than a feature of an element, which probably why CSS 3 is renaming it to the child combinator).




回答2:


Correct, the first rule is more specific than the second, because a class only selector has a fairly low priority.




回答3:


.seven-col has 1 class = +1

div.form-square > div has 2 elements and 1 class = +3

Check it out with this CSS specificity calculator: http://www.suzyit.com/tools/specificity.php



来源:https://stackoverflow.com/questions/7160874/css-child-selector-higher-precedence-than-class-selecctor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!