25

I was wondering why position: sticky works for some x-axis-scrolling, but once you scroll past the initial width of the screen width, your 'sticky div', stops sticking.

In this example, I have a left-side-bar that sticks to the left (please note that I cannot use position: fixed or position: absolute, because in my actual project both the left-div and the right-div need to scroll up and down along the y-axis, hence we only want left-side-sticking)

is there an additional CSS parameter I can define, such as

left-sticky-distance=999999%

or something like that?

some test code illustrating is below

    <html>


    <body>

    <div style='
    position:sticky;
    z-index:1;
    left:0;
    width:100px;
    height:200px;
    overflow: hidden;
    background-color:#ff0000;
    opacity:0.8;'
    >

    </div>

      <div style='position: absolute; top: 10; left: 10; width: 200; height:50px; background-color: blue'>B</div>
      <div style='position: absolute; top: 10; left: 110; width: 200; height:50px; background-color: blue'>C</div>
      <div style='position: absolute; top: 10; left: 210; width: 200; height:50px; background-color: blue'>D</div>
    </body>
    <html>
user1709076
  • 2,538
  • 9
  • 38
  • 59

3 Answers3

38

After I add the height: auto; into body's CSS attributes as below, this auto-hiding problem is fixed.

body {
    background: #fff;
    color: #444;
    font-family: "Open Sans", sans-serif;
    height: auto;
}

Hope it will be helpful to you. :)

Waldeinsamkeit
  • 481
  • 4
  • 3
20

This question: https://stackoverflow.com/a/45530506 answers the problem.

Once the "sticky div" reaches the edge of the screen, it is at the end of the viewport of the parent element. This causes the sticky element to stop and stay at the end of parent's viewport. This code pen provides an example: https://codepen.io/anon/pen/JOOBxg

#parent{
      width: 1000px;
      height: 1000px;
      background-color: red;
}
#child{
      width: 200px;
      height: 200px;
      background-color: blue;
      position: sticky;
      top: 0px;
      left: 0px;
}
body{  
      width: 3000px;
      height: 3000px;
}
<html>
  <div id="parent">
    <div id="child">
    </div>
  </div>
</html>

   
Anthony Bauer
  • 359
  • 2
  • 7
  • 1
    Instead of using height: 1000px; one should use height: auto; to the parent element it will automatically adjust its height to allow its content to be displayed correctly. – Code With Bishal Jun 16 '23 at 20:28
1

What i've just realized is that is stops sticking because you haven't captured an overflow. if you've specified an overflow: hidden;, then check that all content within that axis fits perfectly on all screen sizes and if not then make the necessary adjustments to make the content fit. This also happens when you have specified the height of a div and the content overflows past that height in a certain screen sizes.

I hope this helps anyone that made the same mistake i did.

Junki
  • 11
  • 1