在为父宽度设置动画时居中图像?

时间:2016-09-30 18:34:46

标签: css animation

我有一个div作为图像的视口。我希望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>

我唯一不喜欢的是将图片网址放在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,以便事情的行为与我的第一种方法完全相同?

1 个答案:

答案 0 :(得分:2)

看看这个,我已将will-change: transform;添加到.image2 img,这意味着它会将动画提供给GPU。它看起来更好吗?

这里有一些info

&#13;
&#13;
.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;
}
&#13;
<div class="image2">
  <img src="http://www.oxfordproperties.com/corp/images/investmentCaseStudy/900NewYorkAvenue-main.jpg" />
</div>
&#13;
&#13;
&#13;