【问题标题】:Why does absolutely positioned container cause its children to shake while animating?为什么绝对定位的容器会导致其孩子在动画时晃动?
【发布时间】:2021-11-19 22:50:50
【问题描述】:

考虑以下演示: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,而不使用绝对定位,这样就解决了问题。但对于我的项目,我需要绝对定位。我尝试使用this solution,但没有成功。

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

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

【问题讨论】:

    标签: html css css-animations css-transitions


    【解决方案1】:

    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>

    【讨论】:

    • 我能想到的是将“.inner”从翻译中删除,因此无需调整大小。请注意,您不应该将段落放入锚标记中。
    • 这基本上是我最终在我的项目中所做的。这个解决方案对我来说的问题是,我的.outer.inner 没有固定高度。内容(在我们的示例中为 hello)是动态的。所以,我也不得不重复.outer中的所有内容。
    • 固定高度不会影响垂直居中。我想我不明白这个问题。
    • 如果包含对更改的一些解释,这个答案会更好。
    • @Azu 我碰巧有图标和文本行,文本是动态的,可以跨越两行,所以分配固定高度不是我的选择。
    猜你喜欢
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多