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
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.
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.
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).
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.
Sticky works that way, it will remain sticky
relative to its parent. You need to use fixed
.
Check this codepen
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With