How does CSS specificity decide which styles to apply?

那年仲夏 提交于 2019-11-27 15:40:26

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

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

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

I would suggest you get familiar with this for future reference. For this particular case, note point 3 under Cascading Order:

  1. Count the number of ID attributes in the selector.
  2. Count the number of CLASS attributes in the selector.
  3. Count the number of HTML tag names in the selector.

If these are applied to your code, .item a has 1 class attribute + 1 HTML tag name, while .special has only one class attribute. Hence, the former wins the right to style the special link.

http://www.w3.org/TR/CSS21/cascade.html#specificity is the official specificity specification.

But if that's TL;DR, the (too) short version is the more words you have in your selector, the higher the specificity. And with !important even higher. That's about it.

Edit: oh, I see that your link has the same information as mine. Sorry about that.

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