Change Image on Hover in Pure CSS
In this post I am going to share simple CSS code snippet to Change Image on Hover. If you are looking to add swap image feature while visitor hover on any image then this pure CSS code is for you. You can easily integrate this code snippet in your web based project and apply Change Image on Hover effect to display front and back part of image.
HTML
Here we use HTML5 figure element and place image front and back part.
<figure class="swap-on-hover"> <img class="swap-on-hover__front-image" src="https://c402277.ssl.cf1.rackcdn.com/photos/1620/images/carousel_small/bengal-tiger-why-matter_7341043.jpg?1345548942"/> <img class="swap-on-hover__back-image" src="http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg"/> </figure> |
CSS
Now adding CSS and making your images changeable while hover. By default image front look will display and when ever you hover on image you can display back part of image.
body { background-color: orange; margin: 50px auto; box-sizing: border-box; } /* Make the container relative */ .swap-on-hover { position: relative; margin: 0 auto; max-width: 400px; } /* Select the image and make it absolute to the container */ .swap-on-hover img { position: absolute; top:0; left:0; overflow: hidden; /* Sets the width and height for the images*/ width: 400px; height: 400px; } /* We set z-index to be higher than the back image, so it's alwyas on the front. We give it an opacity leaner to .25s, that way when we hover we will get a nice fading effect. */ .swap-on-hover .swap-on-hover__front-image { z-index: 9999; transition: opacity .5s linear; cursor: pointer; } /* When we hover the figure element, the block with .swap-on-hover, we want to use > so the front-image is going to have opacity of 0, which means it will be hidden, to the back image will show */ .swap-on-hover:hover > .swap-on-hover__front-image{ opacity: 0; } |
See live demo and download source code.
DEMO
This awesome script developed by creativeprogrammer, Visit their official codepen repository for more information and follow for future updates.