Change image on hover

On this page

To swap an image when a user hovers over it, the most common and effective method is to place two images in the same container - making the "rollover" image transparent by default. When the user hovers over the container, the "rollover" image becomes opaque.

Hover over this image, to see the rollover image effect in action:

That on-hover rollover effect was achieved purely with CSS & HTML.

Use CSS to swap images

The following CSS styles show you how to change an image on hover:

<style>
    /*
      Rollover Image
     */
    .figure {
        position: relative;
        width: 360px; /* can be omitted for a regular non-lazy image */
        max-width: 100%;
    }
    .figure img.image-hover {
      position: absolute;
      top: 0;
      right: 0;
      left: 0;
      bottom: 0;
      object-fit: contain;
      opacity: 0;
      transition: opacity .2s;
    }
    .figure:hover img.image-hover {
      opacity: 1;
    }
</style>

Use HTML to select images

Below is the HTML code that sets the 2 images used in the rollover effect. There are two methods - either using lazy loading 'pixel perfect resized' responsive images or using a fixed size images that scale to fit in the browser.

Recommended method - with lazy loading 'pixel perfect resized' responsive images (without any browser scaling):

<script src="https://scripts.sirv.com/sirvjs/v3/sirv.js"></script>
<div class="figure">
  <img class="Sirv image-main" src="https://demo.sirv.com/hc/Bose-700-a.jpg?w=10&colorize.color=efefef" data-src="https://demo.sirv.com/hc/Bose-700-a.jpg">
  <img class="Sirv image-hover" data-src="https://demo.sirv.com/hc/Bose-700-b.jpg">
</div>

Alternative method - without lazy loading images, using fixed size imagery (which may be scaled to fit on small screen devices):

<div class="figure">
  <img class="image-main" src="https://demo.sirv.com/hc/Bose-700-a.jpg?w=360" srcset="https://demo.sirv.com/hc/Bose-700-a.jpg?w=720 2x" alt="Demo image 1">
  <img class="image-hover" src="https://demo.sirv.com/hc/Bose-700-b.jpg?w=360" srcset="https://demo.sirv.com/hc/Bose-700-b.jpg?w=720 2x" alt="Demo image 2">
</div>

Recommended method - with a link:

<script src="https://scripts.sirv.com/sirvjs/v3/sirv.js"></script>
<div class="figure">
  <a href="https://www.example.com/">
  <img class="Sirv image-main" src="https://demo.sirv.com/hc/Bose-700-a.jpg?w=10&colorize.color=efefef" data-src="https://demo.sirv.com/hc/Bose-700-a.jpg">
  <img class="Sirv image-hover" data-src="https://demo.sirv.com/hc/Bose-700-b.jpg">
  </a>
</div>

Did this guide help you to understand how you can use CSS to change an image (on hover) and create a rollover image effect, with Sirv? Please let us know, below.

Was this article helpful?

Get help from a Sirv expert