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


当前回答

尽管阅读了整个页面,尝试了所有的方法,但在我的移动设备上,这就是不能工作。没有任何棘手的操作——这是我唯一需要它发挥作用的地方。我已经排除了任何特殊的名称或覆盖,将阻止它在这个屏幕宽度的功能。清除我的移动格式化代码作为测试,没有看到任何变化。在我笔记本电脑上的Chrome浏览器上运行得很好,但在我的新S10上的Chrome浏览器上就完全不行。

其他回答

这里有两个答案:

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

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

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

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!

我知道太晚了。但我发现了一个解决方案,即使你使用溢出或显示:flex在父元素粘性将工作。

步骤:

为你想要设置粘性的元素创建一个父元素(确保创建的元素是相对于主体或全宽和全高的父元素)。 向父元素添加以下样式: { 位置:绝对的; 身高:100 vmax; } 对于粘滞元素,请确保添加的z-index高于页面中的所有元素。

就是这样!现在它必须起作用。问候

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

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

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

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