当元素包裹在另一个元素中时,为什么position:sticky不起作用? [英] Why position:sticky is not working when the element is wrapped inside another one?

查看:73
本文介绍了当元素包裹在另一个元素中时,为什么position: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>

推荐答案

位置粘性认为父元素的行为应具有应有的作用.在您的情况下,父元素的高度由sticky元素定义,因此该元素没有粘性.

Position sticky consider the parent element to behave as it should be. In your case the parent element has his height defined by the sticky element so there is no room for the element to be sticky.

添加边框以更好地查看问题:

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) 在其中滚动),这时被视为卡住" 直到会议结束 其包含块的相反边缘. ref

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

这篇关于当元素包裹在另一个元素中时,为什么position:sticky不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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