Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

position:sticky does not leave parent

Tags:

css

How can make an element sticky, so it stays at the top of the viewport? I want the element to remain sticky even if it leaves it's container.

I tried this

HTML

<div class="page">
  <div class="parent">
    <div class="child-sticky">
      <p>i want to be sticky, even when I'm outside my parent.</p>
    </div>
  </div>
</div>

CSS

.child-sticky {
  position:sticky;
  top:20px;
}

.page {
  height: 3000px;
}

Here's a pen to illustrate the problem. Scroll down to see what I mean.

https://codepen.io/pwkip/pen/OxeMao

like image 876
Jules Colle Avatar asked Oct 24 '17 14:10

Jules Colle


People also ask

Is position sticky relative to parent?

A sticky element is always relatively positioned to its parent (much like position: absolute; ). This means that these elements will stick and unstick only within the bounds of its parent element, not the viewport (making our job easier); it also means that the thresholds are marked by the edges of the parent.

Why position sticky does not work?

Troubleshooting position sticky Position sticky will most probably not work if overflow is set to hidden, scroll, or auto on any of the parents of the element. Position sticky may not work correctly if any parent element has a set height. Many browsers still do not support sticky positioning.

What is the difference between sticky and fixed position?

An element with position: sticky; is positioned based on the user's scroll position. A sticky element toggles between relative and fixed , depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

What is the role of sticky position?

It allows you to make elements stick when the scroll reaches a certain point. An element with position: sticky will behave like a relatively-positioned element until it reaches a specified point and then starts behaving like a statically-positioned element.


2 Answers

Sticky works that way, it will remain sticky relative to its parent. You need to use fixed. Check this codepen

like image 98
Nicholas Avatar answered Sep 20 '22 14:09

Nicholas


Already 7 months ago, but I found a CSS only solution if the element you want to be sticky is the last one of its parent, its very simple: Just give the parent element position: sticky; and also give it top: -xx;, depending on the height of the elements before the last one.

#parent {
  position: -webkit-sticky;
  position: sticky;
  top: -3em;
}

#some_content {
  height: 3em;
}

#sticky {
  background-color: red;
}

#space {
  height: 200vh;
}
<div id="parent">
  <div id="some_content">Some Content</div>
  <div id="sticky">Sticky div</div>
</div>

<div id="space"></div>
<p>Scroll here</p>
like image 31
Luka Theisen Avatar answered Sep 19 '22 14:09

Luka Theisen