导航栏:位置 Absolute 和 Sticky

Navigation bar : position Absolute and Sticky

我正在尝试制作一个导航栏 与我的 header 重叠 并固定在滚动条 window 的顶部。
它将从 top: 45px 开始并在滚动时停留在 top: 0

我的第一个方法是将其设置为 position: fixed; top: 45px 并在 scroll 事件中使用 JS 更改值。但是 Firefox 给了我关于 .

上讨论的“异步平移”的警告

我已经能够通过一些 CSS 技巧来做到这一点,但我想知道是否有 更简单的 CSS 方法或有效的 JS 方法 执行此操作(不发出警告)。

body {
  position: relative;
  height: 100%;
  width: 100%;
  background-color: grey;
  overflow-x: hidden;
  margin: 0;
}

.container {
  position: absolute;
  top: 0;
  left: -1px;
  width: 1px;
  bottom: 0;
  padding-top: 45px;
  overflow: visible;
}

nav {
  position: sticky;
  top: 0;
  transform: translateX(-50%);
  margin-left: 50vw;
  width: 300px;
  height: 70px;
  background-color: red;
}

header {
  height: 50vh;
  background-color: blue;
}

main {
  height: 200vh;
  width: 100%;
  background-color: green;
}
<div class="container">
  <nav></nav>
</div>
<header>
</header>
<main>
</main>

您可以简化代码并避免使用额外的容器:

body {
  background-color: grey;
  margin: 0;
}

nav {
  position: sticky;
  top: 0;
  width: 300px;
  height: 70px;
  margin:45px auto -115px; /* 115 = height + margin-top */
  background-color: red;
}

header {
  height: 50vh;
  background-color: blue;
}

main {
  height: 200vh;
  background-color: green;
}
<nav></nav>
<header>
</header>
<main>
</main>