Recently I was delighted to discover that all major desktop browsers (Chrome, Firefox, Edge and Safari) now support the CSS property
First create two divs. One represents the main page content and should extend past the bottom of the screen. The second will be the sidebar. We use flex to position them side-by-side, because it’s 2018 and also because I love flex.
Use the following HTML and CSS:
border: 3px solid black;
This gives us two elements that look like this:
Note the heights of the main and sidebar elements are set using vh units. 100vh is the height of the current viewport, so setting the height of the main div to 150vh gives it a height that will be 1.5 times that of the screen.
But the sidebar isn’t sticky yet! When you scroll down the page, the sidebar doesn’t follow. All we need to do to fix that is to add two lines of CSS:
(OK I lied, three lines for Safari compatibility with the
-webkit- prefix.) And there you have it, scroll down the page and the sidebar will stick to the top of the screen and follow you down!
position: sticky property tells the element to stick to the screen, (MDN can explain this better than me), and the
top value tells the element where to sit relative to the screen as it scrolls. We could change this to
top: 5%to leave a gap, or for even
left: 0, if we wanted it to stick as we scrolled left-to-right instead.
Here is one I made earlier on CodePen:
Try changing the height of the sidebar to 110vh and see how it stops at the bottom of the screen. Nice!
Can I use position: sticky in production?
position: sticky is still an experimental API, so use with caution. Read the draft spec here. If you decide to use this property, consider which browsers you support. Combine this with the stats on caniuse to make an informed decision. (Make sure to use the stats for all browsers on caniuse and not just the newest versions.) Ask yourself, how would it affect the user’s experience if the sidebar wasn’t sticky? Would the website break completely or would they lose a nice-to-have decorative feature?
As always, it depends on your particular app and there isn’t an answer that applies to every situation. But it’s really cool that we can now build features like this purely with CSS and a handy tool to have in your CSS toolkit.