johnny
johnny

Reputation: 1251

CSS selector question

.menu a:hover {color: red;} 
.tab:hover {color:blue;}

<div class="menu">
    <a class="tab">Link</a> // will be red
</div>

Why should I use a.tab:hover to override .menu a:hover? Why just .tab:hoverdoesn't work?

Upvotes: 1

Views: 71

Answers (3)

Quentin
Quentin

Reputation: 943142

.menu a:hover is more specific than .tab:hover, so it appears lower down the cascade order.

a.tab:hover is as specific as .menu a:hover, so the rules in those two rule-sets are applied in source order.

Upvotes: 5

Chris Morgan
Chris Morgan

Reputation: 90742

The answer here comes down to what is called "specificity". To understand all about it, take a look at the section Calculating a selector's specificity in the CSS3 Selectors specification (there's similar stuff in the CSS2.1 spec).

Considering a base-10 system (because you don't get above a count of 10 for any level it's safe to do so), .menu a:hover ends up with a specificity of 021, but .tab:hover gets a specificity of 020, which is lower, so where a rule is defined in both, the .menu a:hover one will win.

If you were using a.tab:hover, its specificity would be 021, which is equal to .menu a:hover, and so it then amounts to the order in which they are specified which is applied.

Upvotes: 2

Raptor
Raptor

Reputation: 54212

the class .tab must follow the object it is affecting, in this case a, and must be followed by the pseudoclass (or action) you want it to be activated by, in this case :hover

Therefore, a.tab:hover works while .tab:hover does not

Upvotes: -2

Related Questions