These days I had to rewrite a few elements on different pages to use a position sticky. Mainly navigations menus needed to be sticky at the top of the screen as the user scrolls down.
While refactoring these components I've seen a few common issues that were preventing the position:sticky
to do its job. Let's see them one by one:
- Position sticky works only if any of the
top
,left
,bottom
,right
props is set. It will not work without one of these values. - Check if a parent element has the overflow property set to
scroll
,hidden
, orauto
. If the overflow of a parent is set to anything else than the default value (visible
) then it may break your sticky element. - And maybe the most tricky: if the direct ancestor of the sticky element has
display:flex
then be sure to have on the sticky elementalign-self: flex-start
.
By the way, if you are interested to find out more about CSS layout and other frontend tips you can sign up for my newsletter. You can check out here and here some examples of the js-craft newsletter.
Found this article to be quite helpful while debugging the "stickiness" of an element. Cool stuff! I really like the JS script from the article. You can paste in the dev tools to check if the overflow of a parent breaks the sticky position:
let parent = document.querySelector('.sticky').parentElement;
while (parent) {
const hasOverflow = getComputedStyle(parent).overflow;
if (hasOverflow !== 'visible') {
console.log(hasOverflow, parent);
}
parent = parent.parentElement;
}
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.