Positioning
CSS Position Sticky
Sticky Positioning in CSS
CSS position sticky holds elements during scroll, with browser support.
Understanding Position Sticky
The CSS position: sticky;
property is a hybrid between relative
and fixed
positioning. It allows an element to "stick" to a defined position within its container when the user scrolls, while remaining relative in its initial position. This feature is particularly useful for keeping headers, menus, or any important elements visible as users scroll through content.
How Position Sticky Works
When an element is set to position: sticky;
, it will scroll with the rest of the content until it reaches a specific offset value relative to its containing block. Once this offset is met, the element "sticks" to the position, until the containing block is out of view.
To achieve this, you need to specify one or more of the following properties: top
, right
, bottom
, or left
. These define the offset and determine when the element should become sticky.
Practical Example
Let's consider a scenario where you want to keep a navigation bar at the top of the page. As users scroll down, the navigation bar should remain visible at the top of the viewport.
Browser Support for Position Sticky
The position: sticky;
property is widely supported in modern browsers, including the latest versions of Chrome, Firefox, Safari, and Edge. However, it's always a good practice to verify the compatibility, especially if you're supporting older browser versions.
For the most up-to-date browser support information, consider checking resources like Can I use.
Positioning
- Position Relative
- Position Absolute
- Position Fixed
- Position Sticky
- Z-Index
- Previous
- Position Fixed
- Next
- Z-Index