0

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;
}
Luc
  • 53
  • 1
  • 10
  • 3
    Do you have other CSS rules that are taking precedence over the a:hover? – j08691 Jul 07 '16 at 23:59
  • No. I have some other rules in which I use the :hover selector, but those are all affecting other elements. – Luc Jul 08 '16 at 00:01
  • 3
    Can you post a [mcve] in your question please? – j08691 Jul 08 '16 at 00:01
  • @j08691 Of course, my bad. I thought this was just a simple, stupid question. :) – Luc Jul 08 '16 at 00:10
  • 1
    See [CSS Specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity). – showdev Jul 08 '16 at 00:13
  • Possible duplicate of [CSS Specificity - How does “it” decide which styles to apply?](http://stackoverflow.com/q/9133570/1529630) – Oriol Jul 08 '16 at 00:27

1 Answers1

5

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    my type of answer :) – dippas Jul 08 '16 at 00:24
  • Thanks for typing out the suspicions I already had regarding the problem after reading the article in the comments. This makes it clear to me, thank you! I will use the specific selector as long as it doesn't become unmaintainable. Otherwise, adding !important after the style will do. ;) – Luc Jul 08 '16 at 00:25