How to Make an Element Stick to the Top with CSS
To make an element stick to the top in CSS, use
position: sticky; with top: 0;. Alternatively, use position: fixed; and top: 0; to fix it at the top of the viewport.Syntax
The main CSS properties to make an element stick to the top are:
position: Controls how the element is positioned. Usestickyorfixed.top: Sets the distance from the top edge. Use0to stick exactly at the top.
position: sticky; makes the element stick within its parent container when scrolling.
position: fixed; makes the element stay fixed at the top of the viewport regardless of scrolling.
css
/* Sticky position syntax */ element { position: sticky; top: 0; } /* Fixed position syntax */ element { position: fixed; top: 0; }
Example
This example shows a header that sticks to the top of the page when you scroll down using position: sticky;. The header stays visible inside its container.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Sticky Header Example</title> <style> body { margin: 0; font-family: Arial, sans-serif; } header { position: sticky; top: 0; background-color: #4CAF50; color: white; padding: 1rem; font-size: 1.5rem; z-index: 1000; } main { height: 1500px; padding: 1rem; background: linear-gradient(white, lightgray); } </style> </head> <body> <header>Sticky Header</header> <main> <p>Scroll down to see the header stick to the top.</p> </main> </body> </html>
Output
A green header bar with white text labeled 'Sticky Header' stays visible at the top of the page as you scroll down the tall content area.
Common Pitfalls
- Missing
topvalue: Withouttop: 0;, sticky positioning won't work. - Parent overflow: If a parent container has
overflow: hidden;oroverflow: auto;, sticky may not work properly. - Using
position: fixed;removes element from flow: Fixed elements do not take space and can overlap content.
Always test sticky behavior in the context of your layout.
css
/* Wrong: Missing top value */ element { position: sticky; /* top: 0; missing */ } /* Correct: Include top */ element { position: sticky; top: 0; }
Quick Reference
| Property | Value | Effect |
|---|---|---|
| position | sticky | Element sticks within its container when scrolling |
| position | fixed | Element stays fixed at viewport top, ignoring scroll |
| top | 0 | Sets element to stick exactly at the top edge |
| z-index | number | Controls stacking order to keep element above others |
Key Takeaways
Use position: sticky with top: 0 to make an element stick inside its container when scrolling.
Use position: fixed with top: 0 to fix an element at the top of the viewport regardless of scroll.
Always set top property; sticky won't work without it.
Check parent containers for overflow properties that can block sticky behavior.
Fixed elements are removed from normal flow and can overlap other content.