How To Zoom Image on Hover with CSS

In this article we will use CSS transitions and transforms properties to zoom image on hover.

HTML

<div>
  <img src="earth.jpg" alt="earth image">
</div>

CSS

html {
    box-sizing: border-box;
}

*,
*::after,
*::before {
    box-sizing: inherit;
}

body {
    padding: 0;
    margin: 0;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

This will center div.

Now let’s give height and width to div.

div {
    width: 500px;
    height: 500px;
}

But now image is going to be too big for the container. To illustrate it, I have given red border to div. You can see that image is too big and outside container.

zoom image hover

To fit the image inside the container, add the following css code.

img {
    width: 100%;
}

Now to zoom image on hover, add the following code.

div:hover img {
    transform: scale(1.7);
}

To make it smooth zoom in, add the following code.

img {
    width: 100%;
    transition: all 0.5s;
}

Now the image scales smoothly but it goes outside the container as illustrated by the diagram below.

zoom image hover

To confine the overflow of the image, add the following code.

div {
    width: 500px;
    height: 500px;
    overflow: hidden;
}

Complete CSS Code

html {
    box-sizing: border-box;
}

*,
*::after,
*::before {
    box-sizing: inherit;
}

body {
    padding: 0;
    margin: 0;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

div {
    width: 500px;
    height: 500px;
    overflow: hidden;
}

img {
    width: 100%;
    transition: all 0.5s;
}

div:hover img {
    transform: scale(1.7);
}