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