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

5
我正在尝试创建一个导航栏,它会重叠在我的标题上并在滚动时固定在窗口顶部。
它将从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>


实际解决方案有什么问题?你所说的“适当的解决方案”是什么意思? - Temani Afif
我想我会得到那个评论 :) 我对css/js不是很有经验,所以我想出的解决方案感觉有些笨拙。因此,我想知道是否有适当的JS方法或者我错过了什么。无论如何,如果对你来说可以,那对我也可以 ;) - Pierre-Yves Legeay
1个回答

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

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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接