問題描述
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.
推薦答案
它基于 IDs
、classes
和 tags
.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 特性如何決定應用哪些樣式?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!