导航栏:绝对位置和粘性位置

我正在尝试制作一个重叠我的标题的导航栏,并停留在滚动窗口的顶部。
它将从top: 45px开始并在滚动上停留在top: 0

我的第一种方法是将其设置为position: fixed; top: 45px,然后在scroll事件中使用JS更改值。但是Firefox给了我this post上讨论的有关“ 异步平移”的警告。

我已经能够用一些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>

wgzh107109 回答:导航栏:绝对位置和粘性位置

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

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>

本文链接:https://www.f2er.com/3163629.html

大家都在问