I was making a menu list for current page (.active
), and here's my first try:
.menu li:hover,
.menu li:focus {
border-bottom-color: #000;
}
.menu li.active {
border-bottom: 10px solid #888;
}
(For clean page here, I put all on JS Bin.)
However, the hovering effect about tab is not shown as what I want. So I changed the order of the two like below.
.menu li.active {
border-bottom: 10px solid #888;
}
.menu li:hover,
.menu li:focus {
border-bottom-color: #000;
}
Also on JS Bin
Cheers! It now works as I wanted. But the question comes to my mind.
The specificity of .menu li.active
is higher than the .menu li:hover
, basically 20 vs 11. But why it only works when .menu li.active
is before the .menu li:hover
(the second area of code above)?
Is that because, for the code area 1, we specified the border color of .menu li:hover
first, then we meet the .menu li.active
, and it's border color is not specified when hovering?
(Don't know it's clear or not. It's kinda hard to explain.)
Classes and pseudo-classes have the same specificity. .menu li.active
therefore has the same 'weight' as .menu li:hover
.
Formula, explained (among others) on CSS Specificity: Things You Should Know and CSS Tricks: Specifics on CSS Specificity:
Memorize how to measure specificity. “Start at 0, add 1000 for style attribute, add 100 for each ID, add 10 for each attribute, class or pseudo-class, add 1 for each element name or pseudo-element. So in
body #content .data img:hover
the specificity value would be 122 (0,1,2,2 or 0122): 100 for#content
, 10 for.data
, 10 for:hover
, 1 forbody
and 1 forimg
.”
Applied to your CSS, it would give 21
for both selectors. In case of equal weight, the order is important and the last rule is used.
To make the rule more specific, you can have .menu li.active
for the 'default' styling, and .menu li.active:hover
for the hovered version. The latter is more specific (31 vs 21) than the first and will always be applied on hovering, not matter the order in the CSS file.