3 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!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TABLE OF CONTENTS

Download & Notes Hover Zoom Follow Zoom
Lightbox Useful Bits & Links The End

 

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code in a zip file – I have released it under the MIT License, so feel free to build on top of it if you want to.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

1) HOVER ZOOM

For this first version of the image zoom, we will simply enlarge the entire image as the mouse hovers over it.

 

HOVER ZOOM DEMO

 

HOVER ZOOM HTML & CSS

1a-zoom.html
<style>
.zoomA {
  width: 600px;
  height: auto;
  /* ease | ease-in | ease-out | linear */
  transition: transform ease-in-out 0.3s;
}
.zoomA:hover {
  transform: scale(1.2);
}
</style>
 
<img src="music.jpg" class="zoomA"/>

Yep, that is as simple as it can get. Whoever said image zoom has to be difficult!? For the beginner code ninjas, here is how it works:

  • Define the HTML image tag – <img class="zoomA">.
  • Set the dimensions of the image – .zoomA { width: 600px; height: auto }. Take note, this can either be a fixed or a percentage value.
  • The hover zoom is done with .zoomA:hover { transform: scale(1.2) } and .zoomA { transition: transform }.

If you need a “larger zoom”, just change transform: scale(1.2) to however much is required.

 

 

CONTAINED HOVER ZOOM DEMO

 

CONTAINED HOVER ZOOM HTML & CSS

1b-zoom.html
<style>
.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);
}
</style>
 
<div class="zoomBOut">
  <div class="zoomBIn"></div>
</div>

The above 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 class="zoomBOut"> is the “outer bounding box”, and <div class="zoomBIn"> the image itself.
  • The dimensions are set on the outer box – .zoomBOut { width: 600px; height: 338px; overflow: none; }
  • The image is attached to the inner box as a background image – .zoomBIn { background-image: ulr("music.jpg"); width: 100%; height: 100%; }.
  • The zoom mechanism is the same – .zoomBIn:hover { scale(1.2) } and .zoomBIn { transition: transform }

 

 

2) FOLLOW ZOOM

Ever wonder how some of those eCommerce websites have a nice magnify on the product images that will move along with the mouse? Here’s how.

 

FOLLOW ZOOM DEMO

 

THE HTML & CSS

2a-zoom.html
<style>
#zoom-img {
  width: 600px;
  height: 338px;
  background: url("music.jpg");
  background-position: center;
  background-size: cover;
}
</style>
 
<div id="zoom-img"></div>

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

 

THE JAVASCRIPT

2b-zoom.js
// CREDITS TO https://www.cssscript.com/image-zoom-pan-hover-detail-view/
var addZoom = function (target) {
  // (A) FETCH CONTAINER + IMAGE
  var container = document.getElementById(target),
      imgsrc = container.currentStyle || window.getComputedStyle(container, false),
      imgsrc = imgsrc.backgroundImage.slice(4, -1).replace(/"/g, ""),
      img = new Image();

  // (B) LOAD IMAGE + ATTACH ZOOM
  img.src = imgsrc;
  img.onload = function () {
    var imgWidth = img.naturalWidth,
        imgHeight = img.naturalHeight,
        ratio = imgHeight / imgWidth,
        percentage = ratio * 100 + '%';

    // (C) ZOOM ON MOUSE MOVE
    container.onmousemove = function (e) {
      var boxWidth = container.clientWidth,
          rect = e.target.getBoundingClientRect(),
          xPos = e.clientX - rect.left,
          yPos = e.clientY - rect.top,
          xPercent = xPos / (boxWidth / 100) + "%",
          yPercent = yPos / ((boxWidth * ratio) / 100) + "%";

      Object.assign(container.style, {
        backgroundPosition: xPercent + ' ' + yPercent,
        backgroundSize: imgWidth + 'px'
      });
    };

    // (D) RESET ON MOUSE LEAVE
    container.onmouseleave = function (e) {
      Object.assign(container.style, {
        backgroundPosition: 'center',
        backgroundSize: 'cover'
      });
    };
  }
};

window.addEventListener("load", function(){
  addZoom("zoom-img");
});

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.

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

 

 

ZOOM ON CLICK (LIGHTBOX)

This final method is one of the most traditional ones – Opening up a full-sized image on the screen when the user clicks on the thumbnail.

 

LIGHTBOX DEMO

 

THE HTML

3a-zoom.html
<!-- [LIGHTBOX CONTAINER] -->
<div id="lb-back">
  <div id="lb-img"></div>
</div>

<!-- [THE IMAGES] -->
<img src="music.jpg" class="zoomD"/>

Very simple HTML again, but take note:

  • The lightbox has “2 layers”.
    • <div id="lb-back"> is the background that will cover the entire screen.
    • <div id="lb-img"> will contain the selected image, show it in full size.
  • Nothing special with the images, just the usual <img> tags.

 

THE CSS

3b-zoom.css
/* [IMAGE] */
.zoomD {
  width: 600px;
  height: auto;
  cursor: pointer;
}

/* [LIGHTBOX BACKGROUND] */
#lb-back {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  visibility: hidden;
  opacity: 0;
  transition: all ease 0.4s;
}
#lb-back.show {
  visibility: visible;
  opacity: 1;
}

/* [LIGHTBOX IMAGE] */
#lb-img {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  text-align: center;
}
#lb-img img {
  /* You might want to play around with 
     width, height, max-width, max-height
     to fit portrait / landscape pictures properly. */
  width: 100%;
  height: auto;
 
  /* ALTERNATE EXAMPLE
  width: 100%;
  max-width: 1200px;
  height: auto;
  margin: 0 auto; */
}

/* [DOES NOT MATTER] */
html, body {
  padding: 0;
  margin: 0;
}

There are 3 parts to the CSS:

  • The top part deals with the image thumbnails, which is actually just some simple CSS to restrict the width and height.
  • Then we have #lb-back, literally a full screen “background cover” using width: 100vw and height: 100vh.
  • Finally, the bottom #lb-img deals with the fullsize lightbox image itself. Not much magic here, text-align: center will center the image horizontally. While postion: relative; top: 50%; transform: translateY(-50%); will vertically center the image.

 

 

THE JAVASCRIPT

3c-zoom.js
var zoomImg = function () {
  // (A) CREATE EVIL IMAGE CLONE
  var clone = this.cloneNode();
  clone.classList.remove("zoomD");

  // (B) PUT EVIL CLONE INTO LIGHTBOX
  var lb = document.getElementById("lb-img");
  lb.innerHTML = "";
  lb.appendChild(clone);

  // (C) SHOW LIGHTBOX
  lb = document.getElementById("lb-back");
  lb.classList.add("show");
};

window.addEventListener("load", function(){
  // (D) ATTACH ON CLICK EVENTS TO ALL .ZOOMD IMAGES
  var images = document.getElementsByClassName("zoomD");
  if (images.length>0) {
    for (var img of images) {
      img.addEventListener("click", zoomImg);
    }
  }

  // (E) CLICK EVENT TO HIDE THE LIGHTBOX
  document.getElementById("lb-back").addEventListener("click", function(){
    this.classList.remove("show");
  })
});

The Javascript is where the magic happens.

  • When the window is fully loaded, this script will “seek out” all the images with .zoomD CSS class and attach an onclick event to call zoomImg().
  • zoomImg() simply creates a clone of the selected image, adds it to the lightbox, and displays it.
  • Finally, an onclick event will also be added to the lightbox container so that it will close when the user clicks on it.

 

 

USEFUL 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.

 

YOUTUBE TUTORIAL

 

INFOGRAPHIC CHEAT SHEET

How To Create Image Zoom Effect (click to enlarge)

 

LINKS & REFERENCES

 

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!

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

Leave a Comment

Your email address will not be published. Required fields are marked *