CSS: How to remove background from img hover?

5.9k views Asked by At

I have an underline effect on link hover created without using text-decoration (it must have a different color compared to text)

HTML:

<a href="#">
<img src="https://upload.wikimedia.org/wikipedia/commons/1/16/Custer_Bvt_MG_Geo_A_1865_LC-BH831-365-crop.jpg" />
</a>

CSS:

a:hover {
    background-image: linear-gradient(180deg, rgba(0,0,0,0) 80%, rgba(0,0,0,1) 20%);
}

a:hover img {
    background-image: none !important;
}

img {
  width: 100px;
}

How can I remove the underline from the img on mouse hover? The line should appear only on text links.

Fiddle

This does not work at all: HTML: remove a:hover for images?

1

There are 1 answers

2
Benneb10 On BEST ANSWER

You're going to have to create separate classes in order to accomplish this.

a:hover targets all anchor tags, when you say a:hover img, you are targeting the image inside the anchor tag which has no control over the anchor tags hover effect (the background image).

In order to remove the background-image of the anchor on hover of an image you would need to target a parent which isn't possible in css currently.

I suggest doing the following:

<a href="#">
   <img src="https://upload.wikimedia.org/wikipedia/commons/1/16/Custer_Bvt_MG_Geo_A_1865_LC-BH831-365-crop.jpg" />
</a>
<a class="aText" href="#">
   TESTING
</a>

.aText:hover {
    /*text-decoration:underline;*/
    background-image: linear-gradient(180deg, rgba(0,0,0,0) 80%, rgba(0,0,0,1) 20%);
}

img {
  width: 100px;
}

You may also be able to accomplish this in Javascript.

Possible Javascript you could run onload:

This will search your document for all anchor tags and give the ones that don't contain images the className of "aText". I don't suggest this as a long term solution, only a quick fix.

function addClass(){
 var links = document.getElementsByTagName('a');
 for (var i = 0; i < links.length; i++){
  if( links[i].getElementsByTagName('img').length <= 0){
    links[i].className = "aText"
  }
 }
}