Sticky Scroll in CSS
The position: sticky;
property allows elements to stick to the top (or other edges) of the container as the user scrolls, without using JavaScript.
1. Basic Sticky Example
To make an element stick to the top of its parent when scrolling:
.sticky-header {
position: sticky;
top: 0;
background: white;
z-index: 1000;
}
The element will scroll normally, but when it reaches the top of the viewport, it will stick.
2. Important Notes
- The parent container must have a height that causes scrolling.
- The sticky element will only stick **within** the boundaries of its parent container.
- Use
z-index
to keep it above other content when necessary.
3. Horizontal Sticky
You can also make an element stick horizontally using left
or right
:
.sidebar {
position: sticky;
left: 0;
}
4. When to Use
- Sticky headers and menus
- Sticky sidebars in documentation layouts
- Sticky table headers
5. Browser Support
position: sticky
is widely supported in all modern browsers, but not in older versions of IE. Always test on your target devices.
Conclusion
Sticky positioning is a powerful tool for improving user experience in scrollable interfaces. Use it to keep important UI elements visible while maintaining natural scroll behavior.