CSS 特性如何决定应用哪些样式?

How does CSS specificity decide which styles to apply?(CSS 特性如何决定应用哪些样式?)
本文介绍了CSS 特性如何决定应用哪些样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

CSS 如何确定何时将一种样式应用于另一种样式?

How does CSS determine when to apply one style over another?

我已经阅读了几次W3 CSS3 选择器文档,并且已经帮助我理解了如何在 jQuery 中更好地使用 CSS 选择器,但它并没有真正帮助我理解何时将一个 CSS 规则应用于另一个.

I have been through the W3 CSS3 selectors document a few times, and that has helped me understand how to better use CSS selectors in jQuery, but it has not really helped me understand when one CSS rule will be applied over another.

我有以下 HTML:

<div class='item'>
    <a>Link 1</a>
    <a class='special'>Link 2</a>
</div>

我有以下 CSS:

.item a {
    text-decoration: none;
    color: black;
    font-weight: bold;
    font-size: 1em;
}

.special {
    text-decoration: underline;
    color: red;
    font-weight: normal;
    font-size: 2em;
}

鉴于上述情况,链接 1 和链接 2 的样式将相同,由 .item a CSS 确定.为什么与 .special 关联的样式不优先链接 2?

Given the above, both Link 1 and Link 2 will be styled the same, as determined by the .item a CSS. Why does the style associated with .special not take precedence for Link 2?

显然,我可以像这样绕过它:

Obviously, I can get around it like this:

.special {
    text-decoration: underline !important;
    color: red !important;
    font-weight: normal !important;
    font-size: 1em !important;
}

但是,由于缺乏理解,我觉得这是我必须散布的技巧.

But, I feel like that is a hack that I have to sprinkle in due to my lack of understanding.

推荐答案

它基于 IDsclassestags.IDs 具有最高的特异性,然后是 classes 然后是 tags,所以:

It's based on IDs, classes and tags. IDs have the highest specificity, then classes then tags, so:

.item a     == 0 1 1      0 (id) 1 (class=item) 1 (tag=a)
.special    == 0 1 0
#foo        == 1 0 0
#foo .bar a == 1 1 1
#foo #bar   == 2 0 0

以最多者获胜 :) 如果是平局,则以文件中最后出现的为准.请注意,1 0 0 优于 0 1000 1000

whichever has the most wins :) If it's a tie, whichever one comes last in the document wins. Note that 1 0 0 beats 0 1000 1000

如果您希望 .special 应用,请使其更具体:.item a.special

If you want .special to apply, make it more specific: .item a.special

这篇关于CSS 特性如何决定应用哪些样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

:hover:before text-decoration none has no effects?(:hover:before text-decoration none 没有效果?)
Is CSS faster when you are specific?(当您特定时,CSS 会更快吗?)
CSS sibling selectors (select all siblings)(CSS 兄弟选择器(选择所有兄弟))
IE: nth-child() using odd/even isn#39;t working(IE:使用奇数/偶数的 nth-child() 不起作用)
How can I tell if an element is in a shadow DOM?(如何判断一个元素是否在影子 DOM 中?)
Can I use CSS to add a bullet point to any element?(我可以使用 CSS 为任何元素添加项目符号吗?)