DEV Community

Cover image for CSS position fixed vs sticky
Surya Wiguna
Surya Wiguna

Posted on

31 1 1

CSS position fixed vs sticky

CSS position: fixed helped me a lot when I want to make an element inside a web to stay when user scrolling the page. But in some cases, maybe I want that element still scroll along like others but can stay in place when I want it to stay. That's position: sticky will helpful.

What's the difference?

The position: fixed mean fixed to the viewport. We tell it where to position itself (top, bottom, right, or left) and it will stay there when user scrolling.

Meanwhile, when using position: sticky it won't affect until we define offset, like top: 10px. So the element will scroll like others until it reaches the offset and then stay on its position. And it stay within its parent, once the parent scroll off the page it leaves with it.

To see it in action, you can check on my codepen

Which should I use?

It depends, when you want that element simply doesnt move in your website then use fixed. But be careful with position: fixed, it can potentially cover other element.

When you want that element scrolling into view and then stop at certain point, use sticky. Keep in mind, when its parent scrolls off page, it gone with its parent.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (2)

Collapse
 
vitoneto profile image
VITO NETO

The codepen link helps a lot. Thanks

Collapse
 
injectsploit_75 profile image
injectsploit

thank you very useful

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more