简体   繁体   中英

Overlay transparent image on hover

I have a <div> with a background-image . When this is hovered over I would like another image to be placed on top partially transparent so the original image can be seen below.

My current idea involved adding a :hover state and changing the above images display state to visible along with necessary z-index values.

Could someone give me an example with jsfiddle.net implementation?

Why not use opacity ?

The opacity CSS property specifies the transparency of an element, that is, the degree to which the background behind the element is overlaid.

The value applies to the element as a whole, including its contents, even though the value is not inherited by child elements. Thus, an element and its contained children all have the same opacity relative to the element's background, even if the element and its children have different opacities relative to one another.

.myTransparentImage{
   opacity: 0;
}

.myTransparentImage:hover{
   opacity: 0.6; /* it's in pourcentage */
}

This way, the transparent image, on hover, will appear at 60% opacity so you can still see the one below. So it is on top of the other image the whole time but only appears once hovered.

Here is an example in a fiddle: https://jsfiddle.net/5ob6n7nq/

Whipped up a quick example for you. Hit "Run code snippet" to see it in action.

 .image-holder { background: url('http://i.imgur.com/5ln9Vmi.jpg'); height: 500px; width: 500px; position: relative; } .image-holder::before { content: ''; background: url('http://i.imgur.com/khYHDfJ.jpg'); height: 100%; width: 100%; position: absolute; top: 0; left: 0; opacity: 0; transition: opacity .5s; } .image-holder:hover::before { opacity: .5; /* amount of opacity to blend the two images */ } 
 <div class="image-holder"> </div> 

If I correctly understand you: https://jsfiddle.net/3jabz7d3/

<div class="block1">
  <div class="block2"></div>
</div>


.block1 {
  position: relative;
  width: 200px;
  height: 200px;
  background: url(http://writm.com/wp-content/uploads/2016/08/Cat-hd-wallpapers-1080x675.jpg)  no-repeat center center;
  background-size: cover;
}

.block2 {
  position: absolute;
  width: 100%;
  height: 100%;
  background: url(http://www.cats.org.uk/uploads/images/pages/photo_latest14.jpg)  no-repeat center center;
  background-size: cover;
  display: none;
  opacity: 0.3;
}

.block1:hover .block2{
  display: block;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM