48. Positioning Scheme: Sticky (The Best of Both Worlds)
position: sticky is a hybrid position scheme. An element is treated as relative until it hits a specified offset threshold, at which point it becomes fixed relative to the viewport.
How Sticky Positioning Works
- The element is in the normal flow (
relative). - You must define a threshold using one of the offset properties (
top,right,bottom, orleft). - When the container scrolls and the element's edge touches that defined threshold, the element locks (
fixed) until its parent container scrolls completely out of view.
css .sticky-header { position: sticky; top: 0; /* Becomes fixed when the top of the element hits the top of the viewport / background-color: white; padding: 10px; border-bottom: 1px solid #ccc; z-index: 10; / Important for ensuring it overlays other elements */ }
Requirements for Sticky to Work
- The parent container must be large enough to allow the sticky element to scroll for a while.
- A
top,right,bottom, orleftoffset value must be specified. - The parent element must not have
overflow: hidden,scroll, orautoset, as this restricts the scrolling context.