Sticky Positioning
Overview
position: sticky is a hybrid between relative and fixed. An element acts completely normal (relative) as you scroll down the page, until it hits a specific threshold (like the top of the screen). At that exact moment, it magically turns into a fixed element and sticks to the top of the screen while you continue scrolling. Once you scroll past its parent container, it gracefully un-sticks and scrolls away.
Syntax
/* The table header acts normal until it hits 0px from the top of the screen */
th {
position: sticky;
top: 0; /* The threshold to trigger the 'stickiness' */
/* Required: Must have a background color!
Otherwise, the text will scroll underneath it and clash visually. */
background-color: white;
z-index: 10;
}Common Pitfalls
- Forgetting to set a threshold (e.g.,
top: 0). If you just writeposition: sticky;without specifyingtop,bottom,left, orright, it will do absolutely nothing and just act likeposition: relative. - The Overflow Bug: If ANY parent container in the DOM tree up to the
<body>hasoverflow: hidden;,overflow: auto;, oroverflow: scroll;, it will completely breakposition: sticky. The sticky element will stubbornly scroll off the screen.
Interview Questions
sticky element stop sticking and scroll away?A sticky element is physically bounded by its direct parent container. When the bottom edge of the parent container scrolls up past the sticky element, it will push the sticky element off the screen.
Real-World Example
Creating an iOS-style alphabetical contact list where the letter headers stick to the top.
/* HTML:
<section class="letter-group">
<h2 class="sticky-header">A</h2>
<ul>...</ul>
</section>
*/
.sticky-header {
position: sticky;
top: 0;
/* Aesthetic touches */
background: rgba(255, 255, 255, 0.9);
backdrop-filter: blur(5px);
padding: 10px;
}Check Your Knowledge
Test your understanding of Sticky Positioning with these quick questions.