固定导航栏不仅与 position:fixed

fixed navigation bar not only with position:fixed

是否可以固定 HTML 元素,使其在用户滚动时保持在同一位置?

问题是:如果我使用 "position:fixed",元素将失去与容器的关系并改变实际位置。它从网站包装器中弹出(当然),但我希望它保持其位置并且在滚动时也保持该位置。

这可能吗?

使用 css,您只能使用 position:fixed 执行此操作。如果您知道元素的高度,您列出的问题可以有所缓解。您可以在内容周围的元素上设置 margin-top 以使其从顶部偏移。

#topbar {
  height: 5em;
}

#content {
  margin-top: 5em;
}

#topbar {
  position:fixed;
  top:0;
  left:0;
  width:100%;
  height:5em;
  background: yellow;
  border: 1px red dotted;
}

#content {
  margin-top: 5em;
  padding-top: 5px;
  background: #EEEEFF;
  border: 1px blue dotted;
  height: 500em;
}
<div id="topbar">Something in the topbar</div>
<div id="content">This text is magically displayed under the topbar</div>

您可以通过将元素 position 设置为 fixed 来实现此目的,但不要将其设置为 topleftbottomright 参数。

只要你不设置它们,你的元素就会停留在它所属的地方(相对于最初的父定位)

.your-element{
    position: relative;
}

勾选这个fiddle