skip to Main Content

What I am trying to achieve, is when the image hovered it will change to another. But I guess that the anchor tag is preventing that. How to do so without using any event handler for the image tag. Thanks.

Consider the following code:

#imgId:hover {
  background-image: url("https://via.placeholder.com/100/ff0000");
}
<a href=""><img id="imgId" width="40" height="40" src="https://via.placeholder.com/100"></a>

4

Answers


  1. Unfortunately you can’t do that with img tag, but you can try to replace it with div tag instead with the use of background-image, sample here:

    #imgId {
      width: 200px;
      height: 200px;
      background-image: url('https://placekitten.com/200/200'), url('https://placekitten.com/256/256');
      background-size: contain;
      display: inline-block;
    }
    
    a:hover #imgId {
      background-image: url('https://placekitten.com/256/256');
    }
    <a href="https://example.com"><div id="imgId"></div></a>

    (The additional background-image in the non-hover state is just to pre-load the image to prevent flickering, as requested by the requester)

    Login or Signup to reply.
  2. If you’d rather keep the image element you can use an absolutely-positioned pseudo-element as an overlay. Note that I moved the ID to the anchor for this because images don’t have pseudo-elements.

    #imgId {
      position: relative;
      display: inline-block;
    }
    
    #imgId:hover::after {
      content: '';
      position: absolute;
      left: 0;
      width: 100%;
      top: 0;
      height: 100%;
      background-image: url("https://via.placeholder.com/100/ff0000");
    }
    <a id="imgId" href=""><img src="https://via.placeholder.com/100"></a>
    Login or Signup to reply.
  3. I just try doing it with img tag.

    img
    {
      background-image: url("https://via.placeholder.com/100");
      background-repeat: no-repeat;
      width: 100px;
      height: 100px;
    }
    img:hover
    {
      background-image: url("https://via.placeholder.com/100/ff0000");
    }
    <a href="#"><img></a>
    Login or Signup to reply.
  4. You can play with padding to hide the original image:

    #imgId {
      width: 100px;
      height: 100px;
      box-sizing: border-box; /* this is important */
      /* you can define the image here */
      background-image: url("https://via.placeholder.com/100/ff0000");
    }
    /* update only the padding on hover */
    #imgId:hover {
      padding: 50px; /* half the width */
    }
    <a href=""><img id="imgId" width="40" height="40" src="https://via.placeholder.com/100"></a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search