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
1.0k views
in Technique[技术] by (71.8m points)

css - Why position sticky is not working if followed by position absolute element?

Below is the code snippet and if run it, you can see the header element does not stick. I have looked at the at following questions. “Position: sticky;” not Working CSS and HTML and CSS: 'position: sticky' not working when 'height' is defined among many others but it did not help..

Here is my code.

<body style="margin: 0">
  <div id="header" style="height: 50px;width: 100%;position: sticky;top: 0px;background-color: rgb(33, 150, 243);">
    <div>header contents</div>
    <div>header contents</div>
  </div>
  <div id="container" style="position: absolute; top: 50px; left: 0px; width: 100%; background: #ddd;">
    <div style="height: 1000px;">
      <div>some contents</div>
      <br>
      <div>some contents</div>
      <br>
      <div>some contents</div>
      <br>
      <div>some contents</div>
      <br>
      <div>some contents</div>
      <br>
    </div>
  </div>
</body>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Adding border to the body will show you the issue:

<body style="margin: 0;border:2px solid red;">
  <div id="header" style="height: 50px;width: 100%;position: sticky;top: 0px;background-color: rgb(33, 150, 243);">
    <div>header contents</div>
    <div>header contents</div>
  </div>
  <div id="container" style="position: absolute; top: 50px; left: 0px; width: 100%;">
    <div style="height: 1000px;">
      <div>some contents</div>
      <br>
      <div>some contents</div>
      <br>
      <div>some contents</div>
      <br>
      <div>some contents</div>
      <br>
      <div>some contents</div>
      <br>
    </div>
  </div>
</body>

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

...