位置:粘性不起作用 [英] position:sticky is not working

查看:57
本文介绍了位置:粘性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下HTML代码:

I have this HTML code:

<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并设置了position:sticky和top:0.但这是行不通的.最初,我认为Firefox不支持position:sticky,但事实并非如此,因为我能够看到它的有效演示.我在Google上搜索了一下,但没有发现任何帮助.有人知道为什么这行不通吗?

.header has a height of 150px. .navbar has a height of 20px. When the user scrolls, I want .navbar to stick at the top. So I went to the CSS and set position:sticky and top:0. But this didn't work. I initially thought that firefox is not supporting position:sticky, but that's not the case because I was able to see a working demo of it. I googled about it but found nothing helpful. Anyone knows why this is not working?

推荐答案

如果将导航栏移到标题之外,则效果很好.见下文.因此,根据 MDN :

It works fine if you move the navbar outside the header. See below. For the reason, according to MDN:

根据文档的正常流程放置元素,然后根据top,right,底部和左侧.

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(显然,这意味着您不再能看到它了.)

So, when I do not misunderstand, the navbar is positioned at offset 0 within the header as soon as it is scrolled outside the viewport (which, clearly, means, you can't see it anymore).

.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>

这篇关于位置:粘性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆