Dec 23, 2014 in web design
position property to
fixed so it can’t move any further. If we scroll back down, we revert the setting so the element can move downwards again.
The following code will generate this effect:
You can check out a working example of this idea here. What you will notice, if you scroll slowly, is that just as the sticky element hits the top edge of the viewport, the bottom element (“Main document”) jumps upwards. In fact, at the moment at which the sticky property is turned on, the sticky element covers most of the heading of the main document. This is exactly the same effect that you can see on the Google Scholar page and on countless other pages around the web.
What is going on here? What is happening is that as the sticky property is turned on, the sticky box is removed from the layout and displayed on top of the rest of the document. Hence, the height of that box is now missing from the layout, causing the visible jump. The solution is simple, of course: As we take out an element from the layout, we need to insert an alternative one of exactly the same size. The simple solution is to add a copy of the sticky element that we can show or hide as needed. The corresponding code looks as follows:
I have provided a working implementation of this idea here. As you can see, in this example the layout doesn’t jump at all. The scrolling is smooth the whole time.
This is such a simple trick that I’m surprised it is not used more often. Maybe now that I have posted it here, more people will use it, and we’ll see fewer jarring layout jumps.