如何使用CSS在悬停时缩放图像

时间:2019-01-14 22:30:20

标签: css

如何在悬停时使用CSS缩放div内的图像(仅缩放图像而不是潜水)。 看看我在说什么here

3 个答案:

答案 0 :(得分:3)

对@ tim-klein答案进行一些细微修改,以使视频生效

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

答案 1 :(得分:0)

您可以通过使用:hover伪类来完成总体构思。注意:我并没有过分地保持img居中或使用过渡来模仿慢变焦,但是,如果需要,您可以轻松添加这些功能。

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

答案 2 :(得分:0)

多种解决方案。

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


1。使用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。使用嵌套的图片和object-fit

@Alx Lark's答案基本相同,但添加了object-fit以保持图像的长宽比。

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);
}
相关问题