【问题标题】:How to zoom image on hover with CSS如何使用 CSS 在悬停时缩放图像
【发布时间】:2019-01-14 22:30:19
【问题描述】:

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

【问题讨论】:

标签: css


【解决方案1】:

对@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>

【讨论】:

    【解决方案2】:

    几种不同的方法来解决这个问题。

    演示: 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);
    }
    

    【讨论】:

      【解决方案3】:

      您可以通过使用: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>

      【讨论】:

        猜你喜欢
        • 2020-03-13
        • 2016-02-03
        • 1970-01-01
        • 1970-01-01
        • 2018-09-04
        • 2018-12-01
        • 1970-01-01
        • 2019-05-24
        • 2013-03-23
        相关资源
        最近更新 更多