CSS 特异性还是继承?

2022-01-10 00:00:00 css-selectors css css-specificity

我在这里查看过类似的问题,但我没有找到一个特别适合我的案例的问题.

I've looked at similar questions here but I haven't found one particular to my case.

如果我正确阅读了这篇文章:http://css-tricks.com/具体的css-specificity/

If I read this article correctly: http://css-tricks.com/specifics-on-css-specificity/

那么发生的事情对我来说没有意义.有人可以解释这是由于地方,继承还是特殊性吗?我已经删除了所有不相关的 css.

then what is happening doesn't make sense to me. Can someone explain if this is due to locality, inheritance or specificity please? I've stripped out all the unrelated css.

CSS

a:link {font-size:0.875em;color:#005984}
.button {color:#fff}

HTML

<a class="button">Awesome call to action</a>

我最终得到了一个带有蓝色文本的按钮,而不是白色.现在,a 是一个元素,所以它应该比 .button 类具有更低的特异性,不是吗?

I end up with a button that has blue text, instead of white. Now, a is an element, so it should have lower specificity than the .button class, should it not?

感谢您的宝贵时间.

推荐答案

这是由于 特异性:虽然 a 是一个元素类型选择器,它没有类选择器那么具体,但它伴随着一个 :link 伪类,它同样特定于您的 .button 类.因此,类型 + 伪类将比类更具体.

This is due to specificity: although a is an element type selector which is less specific than a class selector, it's accompanied by a :link pseudo-class which is equally specific to your .button class. A type + pseudo-class will therefore be more specific than a class.

这里没有继承,因为我可以看到没有应用于您的元素的父元素样式.继承是指采用父元素的样式.当您看到显示蓝色而不是白色的链接时,这就是 cascade 在工作,而不是继承.

There is no inheritance going on here as there are no parent element styles that I can see being applied to your element. Inheritance refers to adopting styles from parent elements. When you see the link displaying blue instead of white, that's the cascade at work, not inheritance.

Locality 不是 CSS 术语(至少不在其词汇表中),所以我不确定您的意思.

Locality isn't a CSS term (at least not in its glossary), so I'm not sure what you mean by that.

如果你需要你的号召性用语按钮是白色的,只需给它一个 a 选择器,这样你的选择器同样具体,最后的声明将优先:

If you need your call-to-action button to be white, simply give it the a selector as well, so your selectors are equally specific and the last declaration will take precedence:

a:link {font-size:0.875em;color:#005984}
a.button {color:#fff}

相关文章