CSS, How to cover an image with another image while hovering over it?

Viewed 50

I have two overlapping images. When I hover over one, I want it to cover the other (make it first plan). How can I do that?

1 Answers

You could wrap both of the images in a container element and then change the display or opacity of the child images with the hover pseudoclass.

 <!--HTML-->
  <div id="container">
       <img id="imgOnTop"/>
       <img id="imgOnBottom"/>
  </div>

 /* CSS */
 img#imgOnTop {
    opacity: 1;
 }
 img#imgOnBottom {
     opacity:0;
 }
 div#container:hover img#imgOnTop {
     opacity:0;
 }
 div#container:hover img#imgOnBottom {
     opacity:1;
 }

Alternatively, if you don't want to change the HTML markup and the img elements are already right next to each other in the existing HTML, you could use the CSS adjacent child combinator to do the same thing.

img#imgOnTop {
   opacity: 1;
}
img#imgOnBottom {
   opacity:0;
}
img#imgOnTop:hover {
    opacity:0;
}
img#imgOnTop:hover + img#imgOnBottom {
    opacity:1;
}
Related