Edit:
After reviewing my css, I realized I had a giant hole in my head and the actual issue was the simple fact that I hadn't defined a color
rule in bar.css
.footer-link:hover
, so clearly the color rule from foo.css
a:hover
was being applied. CSS 101. Thank goodness it's Friday. I obviously need the weekend. Thanks for your help!
I'm seeing something interesting while working on some UI for a project, and I'm sure it's related to my lack of understanding surrounding CSS specificity. I've done some research and still can't seem to solve my own problem.
Anyway, I have several defined styles for anchor elements contained in two different stylesheets. For simplicity, I'll call them foo.css
and bar.css
. foo.css
is included in the page before bar.css
In foo.css
there are the following rules:
a {
color: #0088cc;
text-decoration: none;
}
a:hover {
color: #0088cc;
}
In bar.css
there are the following rules:
.footer-link {
border: 1px solid transparent;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
color: rgb(150, 150, 150);
font-size: 13px;
line-height: 18px;
margin-right: 6px;
}
.footer-link:hover {
background-color: rgba(255, 191, 254, 0.8);
text-decoration: none;
}
The HTML markup is:
<a href = "#" class = "footer-link">Cheese is really good</a>
It seems that the hover
styles are being applied from foo.css
even though, as I understand it, .footer-link:hover
has a higher specificity. The normal anchor styles are being applied as I would expect.
So my question is:
Why is the hover rule getting applied in foo.css
even though bar.css
is included later in the page and .footer-link:hover
should be a higher specificity than a:hover
?
Thanks in advance!
Both styles are being applied. You are correct that .footer-link:hover
is more specific than a:hover
, but what you are seeing is a combination of both style definitions. This is the cascading part of cascading style sheets.
Your a
and a:hover
styles are applied first, then the higher specificity .footer-link
and .footer-link:hover
styles are applied afterwards, and any of their explicitly defined properties (such as background
) overwrite the previous definitions.
However, since you don't specify the link color
in the .footer-link:hover
style, it inherits the property from a:hover
instead.
The specificity here is working exactly as it's supposed to, you're just a bit confused about how inheritance and specificity work!