Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

position: sticky is not working with top property?

Position: sticky with bottom:10px on div with class sidebar is working as expected but with property top:10px is not working as expected?

With position: sticky with bottom: 10px on div with class sidebar, when we scroll down the div stick to view port with a bottom edge above 10px to the view port.

Similarly with position: sticky with top:10px on div with class sidebar, as we scroll up the div should stick to top with the top edge of div 10px below the viewport.

But it is not working this way, what is the problem?

code: https://jsfiddle.net/c7vxwc7g/

.container{
      /*width: 1654px;*/
      width: 100%;
      background-color: #f0f0f0;
      margin: 0 auto;
    }
    .sidebar{
    	position: sticky;
    	bottom: 10px;
      width: 400px;
      margin: 5px;
      background-color: teal;
      height: 1000px;
      display: inline-block;
    }
    .mainpage{
      width: 1130px;
      margin: 5px;
      margin-left: 0px; 
      background-color: steelblue;
      height: 6000px;
      display: inline-block;
    }
    .footer{
      height: 500px;
      width: 1654;
      margin: 0 auto;
      margin-top: 10px;
      background-color: purple
    }
    .test1{
      background-color: red;
      position: relative;
      left: 0;
      right: 0;
      top: 0;
      height: 200px;
    }
    .test2{
      background-color: red;
      position: relative;
      left: 0;
      right: 0;
      bottom: 0;
      height: 200px;
    }
<body>
    <div class="container">
        <div class="sidebar">
            <div class="test1">test1</div>
            <div class="test2">test2</div>
        </div>
        <div class="mainpage">mainpage</div> 
    </div>
    <div class="footer">footer</div>
</body>
like image 982
Rahul Avatar asked Dec 08 '25 15:12

Rahul


1 Answers

In my case, the parent of the sticky element (the sidebar) had a smaller height than the content => the sticky element wasn't going down more than the sidebar's height.

The solution: I made the sidebar's height equal to the content's height (using display flex on the content's and sidebar's wrapper).

HTML:

<div clas="container">
    <div class="content">This initially has a bigger height than sidebar.</div>
    <div class="sidebar">
        <div class="sticky"></div>
    </div>
</div>

CSS:

.container { dislay: flex; } // By using this I make the sidebar the same height as the content
.sticky { position: sticky; top: 0; }
like image 69
TheoPlatica Avatar answered Dec 11 '25 03:12

TheoPlatica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!