Welcome to OStack Knowledge Sharing 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 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...