Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

html - 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>
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...