为什么当元素包裹在另一个元素中时位置:粘性不起作用?

2022-01-30 00:00:00 html css sticky

我正在尝试使用粘性导航,但遇到了问题.问题是当我将导航放在其他元素中时,它不再具有粘性.

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`,为什么它会做与规范不同的事情?

位置:粘性"在定义高度"时不起作用

相关文章