父元素使用transform导致position:fixed失效的解决方法

3 min read

当父元素中使用 transform 属性时,position: fixed 对元素的定位会受到影响。在这种情况下,应该将子元素的定位方式设置为 fixed 并将其添加到 body 元素中,以避免使用父元素的 transform 效果。例如:

<style>
  .parent {
    position: relative;
    transform: translateX(100px);
  }

  .child {
    position: fixed;
    top: 20px;
    left: 0;
  }
</style>

<div class="parent">
  <div class="child">Fixed position element</div>
</div>

<script>
  // 将子元素添加到 body 元素中
  document.body.appendChild(document.querySelector('.child'));
</script>