How to Create a Sticky Header in HTML with CSS
To create a sticky header in HTML, use the CSS property
position: sticky; on the header element along with top: 0;. This makes the header stay fixed at the top of the page when you scroll down.Syntax
The basic syntax to make an element sticky is to set its CSS position property to sticky and define an offset like top: 0;. This tells the browser to keep the element stuck to the top of the viewport once it reaches that position during scrolling.
- position: sticky; — makes the element sticky.
- top: 0; — sticks the element to the top edge of the viewport.
- z-index: (optional) ensures the header stays above other content.
css
header {
position: sticky;
top: 0;
background-color: white;
z-index: 1000;
}Example
This example shows a simple sticky header that stays visible at the top when you scroll the page content below it.
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: #007acc; color: white; padding: 1rem; font-size: 1.5rem; z-index: 1000; } main { height: 1500px; padding: 1rem; background: linear-gradient(white, #e0e0e0); } </style> </head> <body> <header>Sticky Header</header> <main> <p>Scroll down to see the header stay fixed at the top.</p> </main> </body> </html>
Output
A webpage with a blue header labeled 'Sticky Header' that stays fixed at the top while the page content scrolls underneath.
Common Pitfalls
Some common mistakes when creating sticky headers include:
- Not setting
topproperty, so the sticky effect won't work. - Using
position: fixed;instead ofsticky, which removes the element from the normal flow and can cause layout issues. - Sticky elements require a parent container that does not have
overflow: hidden;oroverflow: auto;because it can block the sticky behavior. - Forgetting to add
z-indexto keep the header above other content.
css
/* Wrong way: missing top property */ header { position: sticky; background-color: yellow; } /* Right way: include top and z-index */ header { position: sticky; top: 0; background-color: yellow; z-index: 10; }
Quick Reference
Remember these key points for sticky headers:
- Use
position: sticky;withtop: 0;on the header. - Ensure the parent container does not block sticky positioning with overflow.
- Add
z-indexto keep the header on top. - Sticky headers work only when scrolling down past the header's original position.
Key Takeaways
Use CSS
position: sticky; and top: 0; to create a sticky header.Add
z-index to keep the header above other page content.Avoid parent containers with
overflow: hidden; or auto; that block sticky behavior.Sticky headers stay fixed only after scrolling past their original position.
Do not confuse
position: sticky; with position: fixed; as they behave differently.