Position sticky
The position: sticky value is the newest and most sophisticated positioning method. It allows an element to behave like position: relative (staying in the normal flow) until a specified scroll position (threshold) is met, at which point it switches behavior to position: fixed (pinning to the viewport).
It is perfect for section headers that you want to scroll with the content until they reach the top of the screen and then stay pinned while their section scrolls by.
Key Characteristics of position: sticky
1. Hybrid Behavior
- Initial State (Before Threshold): The element behaves like
position: relative. It takes up space in the document flow, and thetop,right,bottom, andleftproperties have no effect. - Active State (After Threshold): Once the user scrolls past the point where the element meets its defined offset (e.g.,
top: 0), it behaves likeposition: fixed. It is pinned to the viewport.
2. Requires an Offset Property
A sticky element is meaningless without an associated offset property. You must define at least one of top, right, bottom, or left to specify the point at which the element should "stick."
/* This is an invalid sticky rule */
.element {
position: sticky;
/* Missing top/right/bottom/left */
}
/* This is a valid sticky rule */
.element {
position: sticky;
top: 0; /* Tells the element to stick when its top edge hits the viewport's top edge */
}
3. Limited by the Parent Container (Crucial)
A sticky element will only be able to stick within the boundaries of its immediate parent container. When the parent container scrolls entirely out of the viewport, the sticky child will scroll away with it.
If your sticky header disappears prematurely, the problem is usually that the parent container is not tall enough or is not defined correctly.
Common Use Cases
1. Sticky Section Headers
Ideal for tables or dashboards where you want the section title to remain visible as the user scrolls through the data in that specific section.
.section-header {
position: sticky;
top: 60px; /* Sticks 60px below the fixed main header */
background-color: #f1f1f1;
z-index: 10;
}
2. Sticky Table Headers
Ensuring that table column headers (<th> elements) remain visible as a user scrolls through long tables.
thead th {
position: sticky;
top: 0;
}
Interactive position: sticky Demo
In this demo, the green "Sticky Section Header" is within the overall content area. When you scroll the content:
- The header scrolls normally with the text until its top edge hits the
top: 0position in the viewport. - It pins itself and stays visible while the content below it scrolls underneath.
- Crucially: When the parent Section (the gray container) scrolls entirely off the screen, the sticky header scrolls away with it.