我想让导航栏粘在视口的顶部一旦用户滚动页面,但它不工作,我不知道为什么。如果你可以帮助,这是我的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>


当前回答

我使用了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()
    }
}

其他回答

这里有两个答案:

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

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

我知道这个问题似乎已经有了答案,但我遇到了一个具体的案例,我觉得大多数答案都没有抓住重点。

溢出:隐藏答案覆盖了90%的情况。这或多或少是“粘性导航”的情况。

但是粘性行为最好在容器高度内使用。想象一下,在你网站的右栏中,有一个新闻简报的形式,它可以随着页面向下滚动。 如果sticky元素是容器的唯一子元素,那么容器的大小是完全相同的,并且没有滚动的空间。

你的容器需要是你期望元素滚动的高度。在右列的情况下就是左列的高度。 实现这一点的最佳方法是在列上使用display:table-cell。如果你不能,并且像我一样被float:right困住了,你必须要么猜左列的高度,要么用Javascript计算它。

如果parent有float:属性,它就不起作用。

另一个position: sticky不能工作的常见场景是,如果它的父类有display: flex或display: grid。

在这种情况下发生的是粘性位置在工作,但你看不到它,因为元素被完全拉伸了。尝试使用align-self: baseline降低它的高度,你会看到效果。

// Sticky Code

const stickyItem = document.querySelector(".item- made-sticky")

document.addEventListener(“scroll”, () => { stickyItem.style.transform = translateY(${window.scrollY}px) })