Can someone explain how `position: sticky` works?

0
7
Asked By CuriousCoder92 On

I've been diving into the concept of `position: sticky`, and honestly, after 15 years in web development, I still don't quite get it. I have a specific example that confuses me, which is here: https://codepen.io/g105b/pen/bNdXYGG. The situation is that I need to keep the `site-nav` element inside the `header` for semantic reasons. I think I understand that since `site-nav` is inside the `header`, which is the scrollable container, the `site-nav` won't actually be sticky because the `header` doesn't scroll. But, when I replace `header` with `custom-header`, it works as I expect. Here are my questions: 1) If I switch to ``, what CSS properties can I apply to `

` to achieve similar results? 2) Why does this behavior change with a custom element? I'm struggling to grasp what's going on here!

5 Answers

Answered By DevDynamo88 On

The issue is that `

` is a block-level element by default. If you change its display to inline (like this: `header { display: inline; }`), the `site-nav` will become sticky as expected! This is because sticky elements are contained within their closest non-inline parent. So, if the parent scrolls, the sticky element will too. It’s all about how the browser interprets the display type of the element.

TechieTom -

Right! So, does that mean a sticky element's container is always the closest non-inline element? Just trying to wrap my head around it.

Answered By LearnWithMe21 On

By the way, I found out that `` is a custom element. It doesn’t do anything at first but is handy if you add functionalities later. Just something to keep in mind!

CuriousCoder92 -

Interesting! I didn’t know that. I’m planning to check out custom elements more.

Answered By WebWhizKid On

To clarify, the problem arises because your `` is inside a `

` that scrolls with the page. When you apply `position: sticky`, it's sticky relative to its parent. If you want it to stick, try making the `

` itself sticky by applying `position: sticky` and `top: 0` to it—then it should work as expected!

CuriousCoder92 -

Thanks, this helps! I read in the MDN docs that sticky elements are supposed to intersect with their nearest scrolling ancestor. Makes more sense now!

Answered By FrustratedDev99 On

Yeah, I get the struggle! Honestly, I can never make sticky work how I want it to either. It can be super finicky!

User2Wander -

Phew! Glad I’m not alone in this!

Answered By CSSMaster101 On

Just to add, remember that the sticky behavior is interrupted if it doesn’t have room to move within its parent container. Changing the display of your custom element to block will have the same effect as the default `

`. That's what makes it work!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.