How does CSS determine when to apply one style over another?
I have been through the W3 CSS3 selectors document a few times, and that has helped me understand how to
I would suggest you get familiar with this for future reference. For this particular case, note point 3 under Cascading Order:
- Count the number of ID attributes in the selector.
- Count the number of CLASS attributes in the selector.
- 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.
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
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.