5 Ways to Create Image Zoom With Pure CSS Javascript

Welcome to a tutorial on how to create an image zoom with CSS and Javascript. Need to spice up your image gallery or an e-commerce store? I am sure there are plenty of such “image zoom” plugins floating all over the Internet, so we will do something a little different with this guide.

Instead of giving you more bloated plugins that require 3rd party libraries, we will walk through a few ways of how you can create your own using just pure CSS and vanilla Javascript. Read on!

 

TABLE OF CONTENTS

 

 

IMAGE ZOOM

All right, let us now get into the various ways and examples of doing image zoom in CSS and Javascript.

 

EXAMPLE 1) HOVER ZOOM

1A) HOVER ZOOM DEMO

 

1B) HOVER ZOOM HTML

1-hover.html
<img src="demo.webp" id="zoomA">

That’s right, it’s just the usual <img> tag.

 

1B) HOVER ZOOM CSS

1-hover.css
#zoomA {
  /* (A) OPTIONAL DIMENSIONS */
  width: 600px;
  height: auto;
 
  /* (B) ANIMATE ZOOM */
  /* ease | ease-in | ease-out | linear */
  transition: transform ease-in-out 0.3s;
}
 
/* (C) ZOOM ON HOVER */
#zoomA:hover { transform: scale(1.2); }

Who said image zoom has to be difficult!?

  • (C) The hover zoom is done with #zoomA:hover { transform: scale(1.2) }. If you want a “larger zoom”, simply change the scale.
  • (B) To add zoom animation, we use #zoomA { transition: transform FUNCTION TIME }.
  • (A) The dimensions are actually optional. If you want a responsive image, use width: 100%; height: auto;

 

 

EXAMPLE 2) CONTAINED HOVER ZOOM

2A) CONTAINED HOVER ZOOM DEMO

 

2B) CONTAINED HOVER ZOOM HTML

2-contained.html
<div id="zoomBOut">
  <div id="zoomBIn"></div>
</div>

The previous hover zoom works, but it may cover surrounding text when the image “expands out of place”. So this is an alternative with a “bounding box”:

  • <div id="zoomBOut"> is the “outer bounding box”.
  • <div id="zoomBIn"> the image itself.

 

2C) CONTAINED HOVER ZOOM CSS

2-contained.css
/* (A) OUTER WRAPPER */
#zoomBOut {
  /* (A1) DIMENSIONS */
  width: 600px;
  height: 360px;
 
  /* (A2) HIDE SCROLLBARS */
  overflow: hidden;
}
 
/* (B) INNER WRAPPER */
#zoomBIn {
  /* (B1) FIT OUTER WRAPPER */
  width: 100%;
  height: 100%;
 
  /* (B2) BACKGROUND IMAGE */
  background-image: url("demo.webp");
  background-position: center;
  background-size: cover;
 
  /* (B3) ANIMATE ZOOM */
  transition: transform ease 0.3s;
}
 
/* (C) ZOOM ON HOVER */
#zoomBIn:hover { transform: scale(1.2); }
  • (C) The main zoom mechanism is still the same old #zoomBIn:hover { transform: scale(1.2); }
  • (B) But take note that the image is now a background-image instead.
  • (A) Set dimensions on the outer box #zoomBOut { width: 600px; height: 360px; overflow: none; } will restrict the image from expanding out of boundaries.

 

 

EXAMPLE 3) FOLLOW ZOOM

3A) FOLLOW ZOOM DEMO

 

3B) FOLLOW ZOOM HTML & CSS

3-follow.html
<div id="zoomC"></div>
3-follow.css
#zoomC {
  /* (A) DIMENSIONS */
  width: 600px;
  height: 360px;
 
  /* (B) BACKGROUND IMAGE */
  background: url("demo.webp");
  background-position: center;
  background-size: cover;
}

The HTML and CSS are straightforward for the following zoom. Just a <div id="zoom-img"> wrapper, and setting the image as the background.

 

3C) THE JAVASCRIPT

3-follow.js
// CREDITS : https://www.cssscript.com/image-zoom-pan-hover-detail-view/
var addZoom = target => {
  // (A) GET CONTAINER + IMAGE SOURCE
  let container = document.getElementById(target),
      imgsrc = container.currentStyle || window.getComputedStyle(container, false);
      imgsrc = imgsrc.backgroundImage.slice(4, -1).replace(/"/g, "");
 
  // (B) LOAD IMAGE + ATTACH ZOOM
  let img = new Image();
  img.src = imgsrc;
  img.onload = () => {
    // (B1) CALCULATE ZOOM RATIO
    let ratio = img.naturalHeight / img.naturalWidth,
        percentage = ratio * 100 + "%";
 
    // (B2) ATTACH ZOOM ON MOUSE MOVE
    container.onmousemove = e => {
      let rect = e.target.getBoundingClientRect(),
          xPos = e.clientX - rect.left,
          yPos = e.clientY - rect.top,
          xPercent = xPos / (container.clientWidth / 100) + "%",
          yPercent = yPos / ((container.clientWidth * ratio) / 100) + "%";
 
      Object.assign(container.style, {
        backgroundPosition: xPercent + " " + yPercent,
        backgroundSize: img.naturalWidth + "px"
      });
    };
 
    // (B3) RESET ZOOM ON MOUSE LEAVE
    container.onmouseleave = e => {
      Object.assign(container.style, {
        backgroundPosition: "center",
        backgroundSize: "cover"
      });
    };
  }
};
 
// (C) ATTACH FOLLOW ZOOM
window.onload = () => addZoom("zoomC");

Credits to CSS Script for the original script. The follow-zoom can no longer be done in CSS, and the magic has to happen in Javascript. Not going to run through line-by-line, but the addZoom() function essentially attaches the follow-zoom effect.

  • (A) Basically, get the background-image from <div id="zoomC"> and get the full image dimension.
  • (B) When the mouse hovers over <div id="zoomC">, show the image in full-size instead.
  • (B1 & B2) Then wild Math happens. Read the X and Y positions of the mouse, then translate it as a percentage of the full-sized image.
  • (B3) Finally, as the mouse leaves the container, it will be restored back to the original background image.

 

 

EXAMPLE 4) FULLSCREEN LIGHTBOX

4A) LIGHTBOX DEMO

 

4B) LIGHTBOX HTML

4-lightbox.html
<!-- (A) LIGHTBOX CONTAINER -->
<div id="lightbox"></div>
 
<!-- (B) THE IMAGES -->
<img src="demo.webp" class="zoomD">

Very simple HTML again:

  • <div id="lightbox"> Background of the lightbox, covers the entire window.
  • <img class="zoomD"> The images that you want attach lightbox.

 

4C) LIGHTBOX CSS

4-lightbox.css
/* (A) LIGHTBOX BACKGROUND */
#lightbox {
  /* (A1) COVERS FULLSCREEN */
  position: fixed; z-index: 999;
  top: 0; left: 0;
  width: 100vw; height: 100vh;
 
  /* (A2) BACKGROUND */
  background: rgba(0, 0, 0, 0.5);
 
  /* (A3) CENTER IMAGE ON SCREEN */
  display: flex;
  align-items: center;
  align-items: center;
 
  /* (A4) HIDDEN BY DEFAULT */
  visibility: hidden;
  opacity: 0;
 
  /* (A5) SHOW/HIDE ANIMATION */
  transition: opacity ease 0.4s;
}
 
/* (A6) TOGGLE VISIBILITY */
#lightbox.show {
  visibility: visible;
  opacity: 1;
}
 
/* (B) LIGHTBOX IMAGE */
#lightbox img {
  /* (B1) DIMENSIONS */
  width: 100%;
  height: auto;
 
  /* (B2) IMAGE FIT */
  /* contain | cover | fill | scale-down */
  object-fit: cover;
}
 
/* (C) LIGHTBOX IMAGE - FULLSCREEN ALTERNATIVE *
#lightbox img {
  width: 100vw;
  height: 100vh;
  object-fit: cover;
}

Not going to explain this line-by-line. It may look complicated, but it’s actually just long-winded.

  1. Create a full-screen “background cover”.
  2. How the lightbox image should look like.

 

4D) LIGHTBOX JAVASCRIPT

4-lightbox.js
window.onload = () => {
  // (A) GET LIGHTBOX & ALL .ZOOMD IMAGES
  let all = document.getElementsByClassName("zoomD"),
      lightbox = document.getElementById("lightbox");
 
  // (B) CLICK TO SHOW IMAGE IN LIGHTBOX
  // * SIMPLY CLONE INTO LIGHTBOX & SHOW
  if (all.length>0) { for (let i of all) {
    i.onclick = () => {
      let clone = i.cloneNode();
      clone.className = "";
      lightbox.innerHTML = "";
      lightbox.appendChild(clone);
      lightbox.className = "show";
    };
  }}
 
  // (C) CLICK TO CLOSE LIGHTBOX
  lightbox.onclick = () => lightbox.className = "";
};

The Javascript is where the magic happens.

  1. When the window is fully loaded, this script will “seek out” all the images with .zoomD CSS class and attach an onclick event to display it fullscreen.
  2. When an image is clicked, create a clone, add it to the lightbox and display it.
  3. Click on the lightbox container to close it.

 

 

EXAMPLE 5) FULLSCREEN API

5A) FULLSCREEN DEMO

 

5B) FULLSCREEN HTML

5-fullscreen.html
<img src="demo.webp" class="zoomE">

Lastly, this is another way to create fullscreen images, using the native fullscreen API. For the HTML, we only need <img> tags again.

 

5C) FULLSCREEN JAVASCRIPT

5-fullscreen.js
window.onload = () => {
  // (A) GET ALL IMAGES
  let all = document.getElementsByClassName("zoomE");
 
  // (B) CLICK TO GO FULLSCREEN
  if (all.length>0) { for (let i of all) {
    i.onclick = () => {
      // (B1) EXIT FULLSCREEN
      if (document.fullscreenElement != null || document.webkitFullscreenElement != null) {
        if (document.exitFullscreen) { document.exitFullscreen(); }
        else { document.webkitCancelFullScreen(); }
      }
 
      // (B2) ENTER FULLSCREEN
      else {
        if (i.requestFullscreen) { i.requestFullscreen(); }
        else { i.webkitRequestFullScreen(); }
      }
    };
  }}
};

Loop through all the images – requestFullscreen() to engage fullscreen, exitFullscreen() to exit fullscreen. Easy.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

THE END

Thank you for reading, and we have come to the end of this short tutorial. I hope it has helped you to create a better website, and if you have anything you want to add to this guide, please feel free to comment below. Good luck and happy coding!

6 thoughts on “5 Ways to Create Image Zoom With Pure CSS Javascript”

  1. How can I make it a clickable link? I used this code:

    .zoomBOut {
    width: 600px;
    height: 338px;
    overflow: hidden;
    position: relative;
    }
    .zoomBIn {
    width: 100%;
    height: 100%;
    background-image: url(“music.jpg”);
    background-position: center;
    background-size: cover;
    transition: transform ease 0.3s;
    }
    .zoomBIn:hover {
    transform: scale(1.2);
    }

  2. Its really hard to find out the best articles on google,this website is having amazing articles.

Comments are closed.