Kristian Rafteseth
Kristian Rafteseth

Reputation: 2032

Overriding previously set CSS

My css:

.pic img:hover {
  border: 1px black solid;
}

My html:

<div class="pic">
  <img src="hey.jpg">
  <img class="overlay" src="overlay.jpg">
</div>

I have an "overlay.jpg" that is placed in the bottom corner of the first image. Problem with the css is that the overlay gets the :hover effect too.

The actual code is very complicated, I know the best solution would be to add a class to the first image and hover only that, but that will take more time than what i currently have to get this fixed.

The code has a class for the overlay images though, so I'm asking if theres a way to override the hover by setting some other css for the overlay class.

However .overlay:hover { border: none; } does not do the trick, even if i put it after the css above.

Upvotes: 1

Views: 90

Answers (3)

Josh Harrison
Josh Harrison

Reputation: 6004

As long as overlay always comes after the first image, you can use :first-child to pick only the first image:

.pic img:first-child:hover {
  border: 1px black solid;
}

It's supported in everything (excluding IE6, but I don't count that as a thing.)

Upvotes: 2

Abhitalks
Abhitalks

Reputation: 28437

You can also use the :not selector:

.pic img:not(.overlay):hover {
  border: 1px black solid;
}

This way you won't have to worry about the order of the images and also don't have to worry about specificity by including another reset style.

Upvotes: 1

emmanuel
emmanuel

Reputation: 9615

Your rule is less specific than the previous one so it is getting overridden.

You have to change it to:

.pic .overlay:hover { border: none; }

The concept

Specificity is the means by which a browser decides which property values are the most relevant to an element and gets to be applied. Specificity is only based on the matching rules which are composed of selectors of different sorts.

How is it calculated?

The specificity is calculated on the concatenation of the count of each selectors type. It is not a weight that is applied to the corresponding matching expression.

In case of specificity equality, the latest declaration found in the CSS is applied to the element.

Reference: Specificity

Upvotes: 2

Related Questions