0

Why do I need to define a height for position sticky?

<div class="content">
  <div class="contentGrid"> {# css grid element #}
    {# other stuff #}
    <div class="sideBar"> {# some stuff inside sidebar #} </div>
  </div>
</div>

Does not work:

.sideBar {
    position: sticky;
    top: 0;
}

Does work:

.sideBar {
     position: sticky;
     top: 0;
     height: 100px; // why tho?
}

Why is there a height needed? How can I make this relative to the content? An absolute px height will inevitabely to lead problems down the road.

KSPR
  • 2,212
  • 4
  • 29
  • 46
  • Is there is any other CSS code which can add some extra styling to this element, for example float..? – Mario Boss Mar 10 '20 at 08:20
  • I found some interesting post to read.. Can be useful in your case: https://stackoverflow.com/questions/49848196/position-sticky-not-working-when-height-is-defined – Mario Boss Mar 10 '20 at 08:22
  • @MarioBoss No floats. just flexbox & css grid – KSPR Mar 10 '20 at 08:23
  • Without seeing more of your layout and CSS it's impossible to debug but the short answer to why you need to define height is that you don't and something else is happening. – JHeth Mar 10 '20 at 09:24
  • Actually, if your sideBar div is empty then yes... nothing will render there but that is the same with all block level elements, they have no inherent height. – JHeth Mar 10 '20 at 09:29
  • dangit. then the problem lies somewhere else. `position:sticky` is so hard. – KSPR Mar 10 '20 at 10:25
  • you said you have flexbox so for sure your element is having a full height of its parent due to the stretch effect. Add border to the sticky element and to the parent element to notice this. Let me know if what I said is true so I can redirect you to the correct duplicate – Temani Afif Mar 10 '20 at 12:42
  • @TemaniAfif YES. The sticky element is stretched to it's parent. `align-self: flex-start;` and the whole thing works webdesign is hard – KSPR Mar 10 '20 at 14:04
  • I added 3 relevant duplicates so you can better understand your issue and how sticky works – Temani Afif Mar 10 '20 at 14:52

0 Answers0