Whenever I've taught people about CSS position, I've always warned against using
Browser support for all position values has been great, except for sticky. So, what's the point in using something that's not going to work a lot of the time?
But, I must say, I've now changed my tune! During the build of Frontend Mentor, I was looking for a simple solution to create a sticky menu on the resources page. The menu allows you to jump between categories on the page and is not part of the main header. All it needed to do was stick to the top of the viewport when the element was scrolled to and leave when the container was scrolled past.
Sure, it would be very easy to install an npm package to achieve that effect, but I wanted to use the simplest approach possible.
As I knew this was the exact behaviour offered by
position: sticky; I thought I'd have a look at current browser support:
Not too bad! Over 86% of browsers used around the world support
position: sticky; and pretty much all major modern browsers support it.
But what happens if someone comes to the site on a browser that doesn't support it? Simple! The element just doesn't stick to the viewport. No mass chaos or breaking of the internet. Just no sticky element.
The site's main users are web developers (both current and aspiring). So it was entirely reasonable to assume the vast majority of people accessing the site will do so through a modern browser.
I went ahead and used it, and I must say it put a smile on my face 🙂 Here's the menu bar sticking to the top of the viewport as you scroll down the page:
And here it is un-sticking itself as you scroll past the parent element:
If you'd like to check it out properly, head over to the resources page on the site.
Want to have a sticky sidebar on your blog post page? The basic markup could be as follows:
<!-- parent element --> <section> <article> ... </article> <!-- sticky element --> <aside> ... </aside> </section>
As soon as the
section element moves out of the viewport the
aside will un-stick itself and move off-screen.
So, next time you're in need of a sticky sidebar or a menu, like me, consider using
Single Responsibility Principle (or SRP) is one of the most important concepts in software development. The main idea of this concept is: all pieces of software must have only a single responsibility.