当用户滚动页面时,我想让导航栏粘在视口顶部,但它不起作用,我也不知道为什么.如果您能提供帮助,以下是我的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>

推荐答案

Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.
...
You must specify a threshold with at least one of top, right, bottom, or left for sticky positioning to behave as expected. Otherwise, it will be indistinguishable from relative positioning. [source: MDN]

所以在你的例子中,你必须使用top属性来定义它到底应该粘在哪里.

html, body {
  height: 200%;
}

nav {
  position: sticky;
  position: -webkit-sticky;
  top: 0; /* required */
}

.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;
}
<nav>
  <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>

Html相关问答推荐

如何找到FontAwese图标的Unicode值?

将输入字段下方的两个按钮设置为两侧对齐

Angular /HTML5不会播放本地文件夹中的音频mpeg

HTML+CSS+JS动态选中文本高亮 colored颜色 变化

在一行中对齐文本和图标

assets资源 净值元素不会扩展到涵盖子项

子元素的单一背景

我的Django应用程序中出现模板语法错误

如何用背景色填充边框半径创建的间隙

为什么字体大小而不是 colored颜色 属性适用于元素?

如何将 元素与常规文本垂直对齐

发送带有图像的Google文档作为HTML格式的邮件正文不再起作用

HTML、CSS设计图像出格

当我将鼠标悬停在测试类上时,左侧类的 colored颜色 没有改变

如何使用 CSS Flex 设计一个导航栏,其中一组项目左对齐而另一组项目右对齐?

在 React (NEXT) 中,当我try 进行动态补充时,我无法使用实例this来引用输入

使用 golem 框架在shiny 的应用程序中存储背景图片的位置

HTML 标记未在页面上展开

尽管设置了 width:100% left:0,但居中对齐的 CSS 动画并不对称

我正在创建一个 django 审查系统.我认为我的 HTML 是错误的