Luc van der Zandt Luc van der Zandt - 4 months ago 6
CSS Question

CSS style not applied unless I specify the exact selector

I've got this situation I think is weird, where

a:hover {
color: #FD5454;
}


doesn't work, but

#feed h3 a:hover {
color: #FD5454;
}


does. It has been some time since I used CSS extensively, so I have no idea why. Could someone please explain this to me? It surely must be a stupid question, but I just couldn't figure it out myself. Thank you in advance!

EDIT:
Here's the code it is affecting at the moment:

<div id="feed">
<h2>Follow us on instagram</h2>
<h3><a href="http://www.instagram.com/johndoe">@johndoe</a></h3>
</div>


And here are the complete style rules:

a:link {
text-decoration: none;
color: white;
}

#feed {
text-align: center;
background: url("../img/Feed_bg.jpg") center no-repeat;
height: 100vh;
}

#feed h2 {
color: #789199;
padding-top: 5vh;
}

#feed h3 a {
text-decoration: none;
font-family: "Lato Light";
color: white;
}

/* This is working */
#feed h3 a:hover {
color: #FD5454;
}

/* This is not */
a:hover {
color: #FD5454;
}

Answer

This is a case of CSS specificity. Here, your a:hover selector isn't specific enough to override the #feed h3 a rule. As MDN notes:

The following list of selector types is by increasing specificity:

  1. Type selectors (e.g., h1) and pseudo-elements (e.g., :before).
  2. Class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover).
  3. ID selectors (e.g., #example).

And as you discovered, by adding #feed in front of your hover selector (#feed a:hover) increases the specificity to override the other selector.

jsFiddle example

There are many CSS specificity calculators available online and you can see that a:hover has a specificity of 0011, while #feed a:hover has 0111.

Comments