I need to implement the button that floats over the content on the same position before the window is scrolled to the end and then sticks to the end of content.
In other words, the element acted as relative
till it reaches specified position. Starting from this position behavior changed as fixed
.
So I'm searching for a css way to do this. Or javascript solution, if it's not possible with stylesheet.
Expected result:
When the content block is under specified position:
And when it reaches the end so initial position is below the its bottom edge:
I need to implement the button that floats over the content on the same position before the window is scrolled to the end and then sticks to the end of content.
In other words, the element acted as relative
till it reaches specified position. Starting from this position behavior changed as fixed
.
So I'm searching for a css way to do this. Or javascript solution, if it's not possible with stylesheet.
Expected result:
When the content block is under specified position:
And when it reaches the end so initial position is below the its bottom edge:
Share Improve this question asked Sep 19, 2017 at 16:33 Oleh RybalchenkoOleh Rybalchenko 8,0894 gold badges26 silver badges40 bronze badges2 Answers
Reset to default 3For modern browsers you can use position: sticky
to stick when it reaches the top (or bottom).
Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.
Read more in this MDN article.
.sticky-button {
position: sticky;
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
bottom: 10px;
}
<div style='width: 500px; height: 3000px; background: #ffffcc; padding: 20px'>
<div style='width: 500px; height: 2000px; background: #eeffff; padding: 20px'>
Page content
</div>
<button class='sticky-button'>Load more...</button>
</div>
Browsers supporting (source):
Unfortunately, there isn't a clear spec for this one - the feature is just landed on Webkit and there are some known issues. But for buttons it works well
Try to google for a library that does this.
The concept is easy, but hard to make it patible with all the browsers.
You will need to know:
1.element's height:
element.style.height
2.window height:
window.innerHeight
3.window scroll pos:
document.body.scrollTop
That should be all the parameters you need.
Here is a quick fiddle I just made:
https://jsfiddle/t7j726c1/
Again, I would try to find a library to do this.