The CSS position: sticky
and position: fixed
properties may seem similar, but they serve different purposes. The key difference between the two is that:
- A fixed element is always fixed relative to the viewport;
- A sticky element is initially in the normal flow, becomes fixed at a certain scroll position, and then behaves like a fixed element.
Fixed Position
When an element has position: fixed
, it:
- Is removed from the normal document flow and is positioned relative to the viewport;
- Stays in the same position even when the user scrolls the page.
It is commonly used for creating elements like headers or navigation bars that stay fixed at a specific position in the viewport as the user scrolls the page.
For example:
.fixed {
position: fixed;
top: 0;
left: 0;
background-color: pink;
z-index: 1000;
}
The top
and left
properties in the above example specify the offset from the top and left edge of the viewport, relative to which the fixed element is positioned.
Sticky Position
When an element has position: sticky
, it:
- Is positioned based on the user's scroll position;
- Behaves like relative positioning until the element crosses a specified point, at which it becomes fixed.
It is often used to create headers or navigation bars that appear fixed until the user scrolls to a certain point, at which the element becomes part of the normal flow.
For example:
.sticky {
position: sticky;
top: 0;
background-color: pink;
z-index: 1000;
}
The top
property in the above example specifies the offset from the top edge of the container at which the element becomes sticky. This allows the sticky element to flow within its container till it meets the opposite edge of its containing block.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.