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


当前回答

我相信这篇文章说了很多关于粘性的工作原理

How CSS Position Sticky Really Works! CSS position sticky has two main parts, sticky item & sticky container. Sticky Item — is the element that we defined with the position: sticky styles. The element will float when the viewport position matches the position definition, for example: top: 0px . Sticky Container —is the HTML element which wraps the sticky item. This is the maximum area that the sticky item can float in. When you define an element with position: sticky you’re automatically defining the parent element as a sticky container!

其他回答

我知道这是一个老帖子。但如果有人像我一样,最近才开始摆弄位置:粘性,这可能是有用的。

在我的例子中,我使用position: sticky作为网格项。它没有工作,问题是一个溢出x:隐藏在html元素。只要我删除了该属性,它就工作得很好。有溢出x:隐藏在身体元素似乎工作,但不知道为什么。

注意空网格区域!

在我的例子中,我有这样的东西:

.cart-areas {
    grid-template-columns: 2fr 0.2fr 1.5fr;
    grid-template-areas:
      'order . summary'
      'order . .'
      'order . .';
}

我希望当用户完成结帐表单时,总结网格项具有粘性。它没有工作,因为那些空的网格项(用。标记)。

解决方案是删除这些空项,如下所示:

.cart-areas {
    grid-template-columns: 2fr 0.2fr 1.5fr;
    grid-template-areas:
      'order . summary'
      'order . summary'
      'order . summary';
}

// Sticky Code

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

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

这是什么绊倒了我…我的粘性div是在另一个div,所以父div需要一些额外的内容后粘性div,使父div“足够高”的粘性div,以“滑过”其他内容,因为你向下滚动。

所以在我的情况下,在黏黏的div之后,我必须添加:

    %div{style:"height:600px;"} 
      &nbsp;

(我的应用程序有两个并排的div,左边是一个“高”图像,右边是一个短的数据输入表单,我希望当你向下滚动时,数据输入表单漂浮在图像旁边,这样表单就总是在屏幕上。它不会工作,直到我添加了上面的“额外内容”,这样粘性div就有东西可以“滑动”

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

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