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


当前回答

如果你的父母正在使用显示伸缩,粘滞位置将不起作用。当我在一个溶液中读到这个

由于flex box元素默认为拉伸,因此所有元素的高度都相同,不能滚动。

如果你使用display: flex;在父元素上,你必须添加这个到sticky元素align-self: flex-start;同时设置height为auto height: auto;

这就是sticky元素类的样子

.stick-ontop {
  position: -webkit-sticky !important; // for safari
  position: sticky !important;
  top: 0;
  align-self: flex-start;
  height: auto;
}

其他回答

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

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

display: unset

为我工作

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

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元素的父元素上使用:overflow: hidden、overflow: scroll或overflow: auto。

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