Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

losing hover color when changing background color on an anchor element.

I'm running into this weird issue on one of my projects. I noticed I was repeating myself multiple times with list items in CSS. Instead repeating myself on each list item I only wanted to change the initial background color of each list item. So what did was add in a third class name to the elements I was working on to specifically identify the ones I wanted to change. However when I do this I lose the a:hover color. The only way to get it back is to re-write the a:hover line of code by using either the triple class selector again or a double class (which is still repeating myself). It is strange that I cannot access that element with a single class? Thoughts? NOTE: I commented out the last line of code to show that it works with the double class, which I thought it would work with a single class as well?

Here is a link to an example on codepen that I wrote:

http://codepen.io/anon/pen/KzwmZK

See if this works....

.default.double.turnGreen > li > a:hover { background:lightgreen; }

2 Answers

Steven Parker
Steven Parker
243,318 Points

The problem is that when you set your initial color to green, you did it by creating a rule that had a higher specificity (0 0 3 2) than the rule that includes the hover (0 0 2 2). Higher specificity rules always override those with lower specificity ... UNLESS you make the property in the lower specificity rule important.

So you can do this and the hover will still work:

.default > li > a:hover {
  background:red !important;
}

Or, as William suggested, you can create an additional rule with equal or higher specificity for the hover over the green item (William's rule is 0 0 4 2).

Thanks. I didn't get to use the !important yet in my learning here at tree house. I also didn't know about calculating the specificity. I had to google that and that helps out a lot.

Also I thought a:hover pseudo element would be on it's own and I didn't think a standalone anchor tag <a> would overwrite that.

See if this works..

.default.double.turnGreen > li > a:hover { background:lightgreen; }

That does work and so does the double class rule. This line I would have to re-write the piece of code again.