我有一个 div 作为图像的视口(viewport)。我希望 div 在鼠标悬停时扩大其宽度,并使内部图像保持移动并保持居中。下面的代码正是我想要的:
HTML 和 CSS
.image {
width: 10%;
background: transparent center center;
height: 200px;
transition: width 2s cubic-bezier(.15, .88, 0, .99);
-o-transition: width 2s cubic-bezier(.15, .88, 0, .99);
-ms-transition: width 2s cubic-bezier(.15, .88, 0, .99);
-moz-transition: width 2s cubic-bezier(.15, .88, 0, .99);
-webkit-transition: width 2s cubic-bezier(.15, .88, 0, .99);
}
.image:hover {
width: 70%;
}
<div class="image" style="background-image:url(http://www.oxfordproperties.com/corp/images/investmentCaseStudy/900NewYorkAvenue-main.jpg);"></div>
我唯一不喜欢的就是将图像 url 放在 style 属性中。我希望我的 HTML 标记看起来像这样:
HTML
<div class="image2">
<img src="http://www.oxfordproperties.com/corp/images/investmentCaseStudy/900NewYorkAvenue-main.jpg" />
</div>
我尝试使用此 CSS 代码来达到相同的效果:
.image2 {
position: relative;
width: 10%;
height: 200px;
overflow: hidden;
transition: width 2s cubic-bezier(.15, .88, 0, .99);
-o-transition: width 2s cubic-bezier(.15, .88, 0, .99);
-ms-transition: width 2s cubic-bezier(.15, .88, 0, .99);
-moz-transition: width 2s cubic-bezier(.15, .88, 0, .99);
-webkit-transition: width 2s cubic-bezier(.15, .88, 0, .99);
}
.image2:hover {
width: 70%;
}
.image2 img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<div class="image2">
<img src="http://www.oxfordproperties.com/corp/images/investmentCaseStudy/900NewYorkAvenue-main.jpg" />
</div>
但这样做的问题是,在 Windows 10 上的 Chrome 中,图像有一点晃动(至少在我的电脑上)。当 div 的宽度折叠时,当 div 宽度等于 img 宽度时会出现短暂的震动。如何消除这种震动效应? Edge 浏览器上似乎没有发生这种情况。
是否有更好的方法来编写我的 CSS,以便其行为与我的第一种方法完全相同?
最佳答案
看看这个,我已将 will-change:transform;
添加到 .image2 img
中,这意味着它将向 GPU 提供动画。你觉得这样更好吗?
这里有一些 info就在上面
.image2 {
position: relative;
width: 10%;
height: 200px;
overflow: hidden;
transition: width 2s cubic-bezier(.15, .88, 0, .99);
-o-transition: width 2s cubic-bezier(.15, .88, 0, .99);
-ms-transition: width 2s cubic-bezier(.15, .88, 0, .99);
-moz-transition: width 2s cubic-bezier(.15, .88, 0, .99);
-webkit-transition: width 2s cubic-bezier(.15, .88, 0, .99);
}
.image2:hover {
width: 70%;
}
.image2 img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
will-change: transform;
}
<div class="image2">
<img src="http://www.oxfordproperties.com/corp/images/investmentCaseStudy/900NewYorkAvenue-main.jpg" />
</div>
关于css - 在动画父宽度时将图像居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39797989/