如何将 CSS 缩放应用于图像

3

我需要将图片放大,但是我使用 background-url 的等效方法是:

.fakeImg:hover img{
    transform: scale(1.1);
}

但我只希望图片在 div 内部增大。

当前状态:

enter image description here

目标:

enter image description here

jsfiddle


1
overflow: hidden 添加到 .imgblog - Phix
2个回答

4
你可以调整background-size而不是scale来仅更改background-image

.box {
 width:150px;
 height:150px;
 margin:50px;
 border:2px solid red;
 background-image:url("https://picsum.photos/400/400?image=1068");
 background-size:100% 100%;
 background-position:center;
 transition:1s all;
}
.box:hover {
 background-size:130% 130%;
}
<div class="box">

</div>


4
缩放功能可以正常工作,但您需要为图像的父元素(框架)设置overflow: hidden。以下是一个示例:

.container {
  overflow: hidden;
  width: 200px;
  height: 200px;
}

.image {
  width: 200px;
  height: 200px;
  background-image: url("https://images.pexels.com/photos/658687/pexels-photo-658687.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260");
  background-size: 200px 200px;
  transition: 1s all;
}

.image:hover {
  transform: scale(1.1);
}
<div class="container">
  <div class="image"></div>
</div>


这应该是被接受的答案。使用Transform比改变background-size更好。 - Devin Fields
@DevinFields是否被接受取决于提问者的决定,但您能解释一下为什么更喜欢使用transform吗? :) ... 您可能会注意到,transform将转换所有元素,包括边框、内容、阴影和其他所有内容...但是background size只会更改背景图像,这正是所需的 ;) - Temani Afif
@TemaniAfif的缩放,结合overflow:hidden,将完全实现他想要的效果,并且性能更好,因为变换不会导致新的布局:https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/在这种情况下,这是否非常重要? 不是很大的问题,但也许随着他的项目增长,这些小事情可能会累积。 - Devin Fields
@DevinFields 你分享的链接正是我需要的 :) 因为如果你再读一遍,你会发现背景也不会触发新的布局 ;) 只有比 transform 多一步,所以性能差异根本不是问题... 而且我知道在这种情况下 scale 将会做到所需的效果,但我只是不同意在更通用的情况下使用“preferred”这个词 :) ... 好吧,这最终是一个观点问题 ;) - Temani Afif
@TemaniAfif 我特别提到了布局,但正如你所说,还有更多的步骤。你应该小心不要低估重新绘制可能产生的影响。如果你正在处理经常移动的东西,你会看到 CPU 使用率急剧增加。我怀疑在这种特定情况下,我个人会尽可能地少使用那四个属性之外的动画。 - Devin Fields

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接