首页 > 解决方案 > 为什么绝对定位的容器会导致其子级在动画时晃动?

问题描述

考虑以下演示: https ://jsfiddle.net/p1n3j7cv/

a {
  display: block;
  width: 300px;
  height: 300px;
  background: lightgrey;
  position: relative;
}

a .outer {
  display: block;
  width: 100%;
  background: green;
  min-height: 40px;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  transition: min-height 3s ease;
  display: flex;
  align-items: center;
}

a .inner {
  display: block;
  width: 100%;
  height: 40px;
  background: orange;
}

a:hover .outer {
  min-height: 100%;
}
<a href="">

  <p> Some regular text <br> which spans <br> multiplle lines <br> so that we have <br> lorem ipsum
  </p>
  <span class="outer">
    <span class="inner">
        hello
    </span>
  </span>
</a>

当您将鼠标悬停在灰色块上时,您会看到,随着外部跨度的扩大(过渡),橙色跨度会抖动。这发生在所有主要浏览器上。原因似乎是涉及到绝对定位,如果我后面没有任何内容,我可以不用flex,而不使用绝对位置,这样就解决了问题。但对于我的项目,我需要绝对定位。我尝试使用此解决方案,但没有奏效。

我的猜测是它与动画时不使用 gpu 加速有关min-height。每个像素转换可能都在进行 css 重绘,这会进一步重新计算每个像素移动时的绝对定位元素位置。

问题:为什么会发生震动?

标签: htmlcsscss-animationscss-transitions

解决方案


a {
  display: block;
  width: 300px;
  height: 300px;
  background: lightgrey;
  position: relative;
}

a .outer {
  display: block;
  width: 100%;
  background: green;
  min-height: 40px;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  transition: min-height 3s ease;
  display: flex;
  align-items: center;
  z-index:1

}
a .inner {
  display: block;
  width: 100%;
  height: 40px;
  background: orange;
  position:absolute;
  left:0;
  top: 50%;
  transform:translateY(-50%);
  z-index:2
}

a:hover .outer {
  min-height: 100%;
}
<a href="">
  <span class="outer"></span>
  <span class="inner">hello</span>
</a>


推荐阅读