CSS特异性 - 如何“它”决定应用哪些样式? [英] CSS Specificity - How does "it" decide which styles to apply?

查看:232
本文介绍了CSS特异性 - 如何“它”决定应用哪些样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,CSS如何确定何时将另一种样式应用于另一种样式?

In a nutshell, how does CSS determine when to apply one style over another?

在过去一年中,我一直使用大量JavaScript和jQuery中使用的基于CSS的选择器推动我了解更多关于它们如何工作。我已通过 W3 CSS3选择器文档几次,这有助于我了解如何更好地在jQuery中使用CSS选择器,但它没有真正帮助我理解何时一个CSS规则将应用于另一个。

In the past year, I have been working with a lot of JavaScript and the CSS based selectors used in jQuery pushed me to learn more about how they work. 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.

我会给你一个例子,不明白。

I will show you an example of what I do not understand.

我有以下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 相关联的样式不会优先用于Link 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;    }

但是,我觉得这是一个黑客,我必须洒在由于我缺乏理解。当我使用!important 我觉得有点像一个上瘾者滑倒一些少量的禁止物质,告诉自己在放弃之前放弃一次最后一次是可以的

But, I feel like that is a hack that I have to sprinkle in due to my lack of understanding. When I use !important I feel a little bit like an addict slipping some small amount of a forbidden substance, telling himself it's ok to indulge "one-last-time" before quitting for good.

此外,如果我想真正学习CSS,是否有推荐的优秀书籍?

Additionally, if I wanted to really learn CSS, are there any excellent books to recommend?

推荐答案

它基于 IDs classes 标签具有最高的特异性,然后,然后标签所以:

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 beats 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特异性 - 如何“它”决定应用哪些样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆