I am trying to fix a div
so it always sticks to the top of the screen, using:
position: fixed;
top: 0px;
right: 0px;
However,
2019 SOLUTION: You can use position: sticky
property.
Here is an example CODEPEN demonstrating the usage and also how it differs from position: fixed
.
How it behaves is explained below:
An element with sticky position is positioned based on the user's scroll position. It basically acts like position: relative
until an element is scrolled beyond a specific offset, in which case it turns into position: fixed. When it is scrolled back it gets back to its previous (relative) position.
It effects the flow of other elements in the page ie occupies a specific space on the page(just like position: relative
).
If it is defined inside some container, it is positioned with respect to that container. If the container has some overflow(scroll), depending on the scroll offset it turns into position:fixed.
So if you want to achieve the fixed functionality but inside a container, use sticky.