Why position:sticky is not working when the element is wrapped inside another one?(为什么当元素包裹在另一个元素中时位置:粘性不起作用?)
问题描述
我正在尝试使用粘性导航,但遇到了问题.问题是当我将导航放在其他元素中时,它不再具有粘性.
I am experimenting with sticky nav and I ran into problem. Problem is that when I put the nav in other element it's not anymore sticky.
.nav-wrapper{
position: absolute;
bottom: 0;
}
.nav-wrapper nav{
position: sticky;
top: 0;
}
<div class="nav-wrapper">
<nav>
<a href="#"><li>Home</li></a>
<a href="#"><li>About</li></a>
</nav>
</div>
推荐答案
position:sticky
考虑父元素的行为.在您的情况下,父元素的高度由粘性元素定义,因此元素没有空间具有粘性行为
position:sticky
consider the parent element to behave as it should be. In your case the parent element has its height defined by the sticky element so there is no room for the element to have a sticky behavior
添加边框以更好地查看问题:
Add border to better see the issue:
.nav-wrapper {
position: absolute;
bottom: 0;
border: 2px solid;
}
.nav-wrapper nav {
position: sticky;
top: 0;
}
body {
min-height:200vh;
}
<div class="nav-wrapper">
<nav>
<a href="#">
<li>Home</li>
</a>
<a href="#">
<li>About</li>
</a>
</nav>
</div>
现在给父元素添加高度,看看发生了什么:
Now add height to the parent element and see what is happening:
.nav-wrapper {
position: absolute;
bottom: 0;
border: 2px solid;
height:80vh;
}
.nav-wrapper nav {
position: sticky;
top: 0;
}
body {
min-height:200vh;
}
<div class="nav-wrapper">
<nav>
<a href="#">
<li>Home</li>
</a>
<a href="#">
<li>About</li>
</a>
</nav>
</div>
粘性行为工作正常,因为父元素上有足够的高度,可以在特定阈值后固定元素.
The sticky behavior is working fine because there is enough height on the parent element where the element can be fixed after a specific threshold.
粘性定位元素是计算位置的元素价值是粘性的.它被视为相对定位直到其包含块超过指定阈值(例如将 top 设置为其流根(或它的容器)内的值而不是 auto在其中滚动),此时它被视为卡住";直到见面其包含块的另一边.参考
A stickily positioned element is an element whose computed position value is sticky. It's treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block.ref
相关问题:
为什么bottom:0 不适用于position:sticky?
如果您为 position:sticky 指定 `bottom: 0`,为什么它会做与规范不同的事情?
位置:粘性"在定义高度"时不起作用
这篇关于为什么当元素包裹在另一个元素中时位置:粘性不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么当元素包裹在另一个元素中时位置:粘性不起作用?
基础教程推荐
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 动态更新多个选择框 2022-01-01