我想让导航栏粘在视口的顶部一旦用户滚动页面,但它不工作,我不知道为什么。如果你可以帮助,这是我的HTML和CSS代码:

.container { min-height: 300vh; } .nav-selections { text-transform: uppercase; letter-spacing: 5px; font: 18px "lato",sans-serif; display: inline-block; text-decoration: none; color: white; padding: 18px; float: right; margin-left: 50px; transition: 1.5s; } .nav-selections:hover{ transition: 1.5s; color: black; } ul { background-color: #B79b58; overflow: auto; } li { list-style-type: none; } <main class="container"> <nav style="position: sticky; position: -webkit-sticky;"> <ul align="left"> <li><a href="#/contact" class="nav-selections" style="margin-right:35px;">Contact</a></li> <li><a href="#/about" class="nav-selections">About</a></li> <li><a href="#/products" class="nav-selections">Products</a></li> <li><a href="#" class="nav-selections">Home</a></li> </ul> </nav> </main>


当前回答

1.如果overflow在元素的任何父元素上设置为hidden、scroll或auto,位置粘滞很可能不起作用。

2.如果任何父元素都设置了高度,位置粘滞可能无法正常工作。

其他回答

这里有两个答案:

从正文标签中移除溢出属性 设定高度:100%到机身以解决溢出问题y:自动

Min-height: 100%不工作,而不是高度:100%

如果你遇到这种情况,你的粘性不工作-试着设置父:

display: unset

为我工作

我使用了JS解决方案。它适用于Firefox和Chrome浏览器。有任何问题,请告诉我。

html

<body>
  <header id="header">
    <h1>Extra-Long Page Heading That Wraps</h1>
    <nav id="nav">
      <ul>
        <li><a href="" title="">Home</a></li>
        <li><a href="" title="">Page 2</a></li>
        <li><a href="" title="">Page 3</a></li>
      </ul>
    </nav>
  </header>
  <main>
    <p><!-- ridiculously long content --></p>
  </main>
  <footer>
    <p>FOOTER CONTENT</p>
  </footer>
  <script src="navbar.js" type="text/javascript"></script>
</body>

css

nav a {
    background: #aaa;
    font-size: 1.2rem;
    text-decoration: none;
    padding: 10px;
}

nav a:hover {
    background: #bbb;
}

nav li {
    background: #aaa;
    padding: 10px 0;

}

nav ul  {
    background: #aaa;
    list-style-type: none;
    margin: 0;
    padding: 0;

}

@media (min-width: 768px) {

    nav ul {
        display: flex;
    }
}

js

function applyNavbarSticky() {
    let header = document.querySelector('body > header:first-child')
    let navbar = document.querySelector('nav')
    header.style.position = 'sticky'

    function setTop() {
        let headerHeight = header.clientHeight
        let navbarHeight = navbar.clientHeight
        let styleTop = navbarHeight - headerHeight

        header.style.top = `${styleTop}px`
    }

    setTop()

    window.onresize = function () {
        setTop()
    }
}

用于位置:粘;要工作,你的sticky元素应该放在body标签的右边,作为一个直接的子元素 不应该有任何包装divs或类似的东西。 因为它只能在到达父元素的底部之前保持固定。 你应该指定它应该粘在哪里,比如:top: 0;

z指数也很重要。有时候它会起作用,只是你看不到而已。试着把它设置为一个非常高的数字,只是为了确定。也不要总是放top: 0,而是尝试一些更高的,以防它被隐藏在某个地方(在工具栏下面)。