What is position sticky in CSS: Explanation and Example
position: sticky in CSS is a way to make an element stick to a position on the screen when you scroll past it, but only within its parent container. It behaves like relative until you scroll to a certain point, then it acts like fixed to stay visible.How It Works
Imagine a sticky note on a page that moves with you as you scroll, but only until you reach the end of the page section it belongs to. position: sticky works similarly. The element starts in its normal place, moving with the page. When you scroll and the element reaches a specified position (like the top of the screen), it sticks there.
Unlike position: fixed, which stays fixed on the screen no matter what, sticky elements only stick within their parent container. When the container scrolls out of view, the sticky element scrolls away too. This makes it great for headers or menus that stay visible while you scroll through a section.
Example
This example shows a header that sticks to the top of the page when you scroll down.
html {
font-family: Arial, sans-serif;
line-height: 1.5;
margin: 0;
padding: 0;
}
.container {
height: 200vh; /* Make page tall to enable scrolling */
padding: 20px;
background: #f0f0f0;
}
.sticky-header {
position: sticky;
top: 0;
background: #007acc;
color: white;
padding: 10px;
font-weight: bold;
font-size: 1.2rem;
border-radius: 4px;
z-index: 10;
}
.content {
margin-top: 20px;
font-size: 1rem;
color: #333;
}When to Use
Use position: sticky when you want an element to stay visible while scrolling, but only within a certain area. Common uses include sticky navigation bars, table headers, or call-to-action buttons that remain accessible as users scroll.
This helps improve user experience by keeping important controls or information in view without taking up permanent screen space.
Key Points
- Sticky elements behave like
relativeuntil a scroll threshold, then act likefixed. - They only stick within their parent container.
- Requires a
top,left,right, orbottomvalue to work. - Great for keeping headers or menus visible during scrolling.
Key Takeaways
position: sticky keeps an element visible by sticking it at a position during scroll within its container.top: 0 to know where to stick.