Picoral
Picoral

Reputation: 318

How to zoom image on hover with CSS

How can I zoom an image that is inside an div on hover using CSS (zoom only the image, not the div). See what I'm talking about here

Upvotes: 6

Views: 12668

Answers (3)

shanomurphy
shanomurphy

Reputation: 706

Couple of different ways to tackle this.

Demo: https://codepen.io/shanomurphy/pen/BvMrWq?editors=1100


1. Using background-image

HTML:

<div class="zoom-bg"></div>

CSS:

.zoom-bg {
  width: 300px;
  height: 200px;
  overflow: hidden;
}

.zoom-bg:before {
  content: '';
  display: block;
  width: 100%;
  height: 100%;
  background: url('https://placeimg.com/300/200/nature') no-repeat center;
  background-size: cover;
  transition: all .3s ease-in-out;
}

.zoom-bg:hover:before {
  transform: scale(1.2);
}

2. Using nested image and object-fit

Basically the same as @Alx Lark's answer but adding object-fit to maintain the aspect ratio of the image.

HTML:

<div class="zoom-img">
  <img src="https://placeimg.com/300/200/arch">
</div>

CSS:

.zoom-img {
  width: 300px;
  height: 200px;
  overflow: hidden;
}

.zoom-img > img {
  object-fit: cover;
  width: 100%;
  height: 100%;
  transition: all .3s ease-in-out;
}

.zoom-img:hover > img {
  transform: scale(1.2);
}

Upvotes: 2

alx lark
alx lark

Reputation: 864

Some minor modifications of @tim-klein answer to get effect from video

.container {
  border: 1px solid black;
  width: 100%;
  height: 184px;
  overflow: hidden;
}

.container img {
  width: 100%;
  height: 100%;
      transition: all 2s ease-in-out;
}

.container:hover img {
      transform: scale(2,2)
}
<div class="container">
  <img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
</div>

Upvotes: 7

Tim Klein
Tim Klein

Reputation: 2758

You can accomplish the general idea by using the :hover pseudo-class. Note: I didn't go overboard with keeping the img centered or using a transition to mimic the slow zoom, however, you could easily add those features if desired.

.container {
  border: 1px solid black;
  width: 100%;
  height: 184px;
  overflow: hidden;
}

.container img {
  width: 100%;
  height: 100%;
}

.container:hover img {
  width: 120%;
  height: 120%;
}
<div class="container">
  <img src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"/>
</div>

Upvotes: 2

Related Questions