css – 位置:粘不起作用

我有这个 HTML

代码:

<div class="header">
<div class="desc">Description</div>
<div class="logo"><img src=""/></div>
<div class="navbar"></div></div>

.header的高度为150px. .navbar的高度为20px.当用户滚动时,我希望.navbar坚持在顶部.所以我去了CSS并设置了位置:sticky和top:0.但这没效果.我最初认为firefox不支持position:sticky,但事实并非如此,因为我能够看到它的工作演示.我用Google搜索但没有发现任何帮助.谁知道为什么这不起作用?

如果您将导航栏移动到标题之外,它可以正常工作.见下文.因此,根据 MDN

The element is positioned according to the normal flow of the document, and then offset relative to its flow root and containing block based on the values of top, right, bottom, and left.

对于包含块:

The containing block is the ancestor to which the element is relatively positioned

因此,当我没有误解时,只要在视口外滚动导航栏,它就会定位在标题内的偏移0处(显然,这意味着,您再也看不到它了).

.navbar {
  background: hotpink;
  width: 100%;
  height: 50px;
  position: -webkit-sticky;
  position: sticky;
  top: 0;
}

.header {
  height: 150px;
  background: grey;
}

body {
  height: 800px;
  position: relative;
}
<div class="header">
<div class="desc">Description</div>
<div class="logo"><img src=""/></div>
</div>

<div class="navbar"></div>

翻译自:https://stackoverflow.com/questions/45530235/positionsticky-is-not-working

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章