Oh yeah there is! At least the most modern browsers support the sticky
value of the position
property which is a solution for the exact usecase you've described.
For example if you have a DOM structure like this:
The top: 0;
part is necessary, to tell the browser where the element should stick to. You could also set left
, right
or bottom
if your element should stick to other areas of the viewport.
You also need to make sure that no parent element above the sticky-position element has set the overflow
property to scroll
, auto
, or hidden
. In order to make it work in safari you also need to set position: -webkit-sticky
.
As already mentioned, the most modern browsers support the sticky
value of the position
property, but for example if you need to support Internet Explorer 11, you will need to implement a workaround with JavaScript. Here you can see a detailed report about browser support for the sticky
value: https://caniuse.com/css-sticky