position: sticky
Sticky positioning is a hybrid between relative and fixed. An element flows normally until a scrolling threshold is reached, then it "sticks" to that position. This is useful for sticky headers and table headers.
Sticky Positioning Basics
CSS
/* Sticky positioning */
.element {
position: sticky;
top: 0;
/* Sticks to top when scrolling reaches it */
}
/* Sticky header */
header {
position: sticky;
top: 0;
background: white;
z-index: 100;
}
/* Header content flows normally, sticks when scrolling */
/* Sticky table headers */
th {
position: sticky;
top: 0;
background: #f0f0f0;
}Common Patterns
CSS
/* Sticky navigation */
nav {
position: sticky;
top: 0;
background: white;
border-bottom: 1px solid #ddd;
z-index: 100;
}
/* Sticky section headers */
h2 {
position: sticky;
top: 60px;
background: white;
padding: 20px;
border-bottom: 1px solid #ddd;
}
/* Sticky sidebar */
.sidebar {
position: sticky;
top: 20px;
height: fit-content;
}Note
Sticky positioning flows normally until a scroll threshold, then sticks. It's useful for headers and navigation. The parent container's height constrains how long sticky works.
Next
Z-index and stacking: [z-index](/css/z-index).