Search code examples
csssticky

How to make a grandchild element sticky?


How do I make it so a left sidepane (grandchild) is sticky relative to the body, but a navbar and the main content are scrollable.

<div>
  <div>navbar (should scroll away)</div>
  <div>
    <div>side pane (should stick to the top of the screen)</div>
    <div>main content (should scroll away)</div>
  </div>
</div>

Solution

  • If I understand your question correctly, your best bet is to move your side pane div out of it's parent div and then set it's position to fixed and change your top, left, etc. styles.

    All that matters in the end is that your side pane div doesn't have any parent, grandparent, etc. with position that isn't static since a fixed div will want to be positioned relative to it's closest ancestor with a position that isn't static. The easiest way is still to move the side pane div outside of all other divs so that it is a direct child of the body.