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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read 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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay