首页 > 解决方案 > 修复了 Firefox 浏览器中粘性父项中的子元素闪烁

问题描述

我正在尝试创建一个带有position: sticky;position: fixed;的标题,其中一个项目和第二个项目没有position: fixed;.

这是实现:Codepen

问题:当我在 Chrome 中打开此 Codepen 时,一切正常,但是当我在 Firefox 中尝试此代码时,会出现奇怪的闪烁。您可以自己尝试,只需向下和向上滚动即可。

以防万一,这里是视频:Youtube 链接

以下是我尝试过的解决方案:

我想要什么:去掉这个你可以在视频上观看的闪烁。

火狐版本:80.0.1 64 位

操作系统:Ubuntu 18.04.5 LTS

注意:这个错误有时可能不会在 Windows 上重现(我不知道为什么),但总是在 Ubuntu 或 macOS 操作系统上重现。对于装有 Windows 的 PC 上的 Firefox 80.0.1,一切正常。

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

body {
  background: skyblue;
  height: 300vh;
}

.header {
  width: 100%;
  height: 250px;
  background: green;
  position: sticky;
  top: -80px;
}

.header__item {
  height: 150px;
  width: 100px;
  background: tomato;
  position: fixed;
  top: 0;
}

.header__second-item {
  height: 80px;
  width: 100px;
  background: purple;
  margin-left: auto;
}
<header class="header">
  <div class="header__item"></div>
  <div class="header__second-item"></div>
</header>

标签: htmlcssfirefox

解决方案


首先,尝试将position: fixed;元素替换为position: sticky; 在 Firefox 中,它会被修复,但 Safari 不支持具有粘性位置的子元素。我看到的唯一方法 - 检测浏览器并根据浏览器替换位置。例如:

.header__item {
  position: fixed;
}

@-moz-document url-prefix() {
  .header__item {
    position: sticky;
  }
}

推荐阅读