Why position:sticky is not working when the element is wrapped inside another one?

前端 未结 1 1846
庸人自扰
庸人自扰 2020-11-22 05:32

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.

相关标签:
1条回答
  • 2020-11-22 06:19

    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.

    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

    0 讨论(0)
提交回复
热议问题