Creating a sticky header using HTML and CSS is straightforward. A sticky header remains visible at the top of the viewport as the user scrolls down the page. You can achieve this using the position: sticky property in CSS.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sticky Header</title> <link rel="stylesheet" href="styles.css"> </head> <body> <header class="sticky-header-demo"> <h1>Sticky Header</h1> <nav> <ul> <li><a href="#section1">Section 1 demo</a></li> <li><a href="#section2">Section 2 demo</a></li> <li><a href="#section3">Section 3 demo</a></li> </ul> </nav> </header> <main> <section id="section1"> <h2>Section 1 demo</h2> <p>Content for section 1...</p> </section> <section id="section2"> <h2>Section 2 demo</h2> <p>Content for section 2...</p> </section> <section id="section3"> <h2>Section 3 emo</h2> <p>Content for section 3...</p> </section> </main> </body> </html>
2. CSS Styling
Add the CSS to style the header and make it sticky.
/* General reset and body styles */
body {
margin: 0;
font-family: Arial, sans-serif;
line-height: 1.6;
}
main {
padding: 20px;
}
/* Sticky header styling */
.sticky-header-demo {
position: sticky;
top: 0; /* The header will stick to the top of the viewport */
background-color: #333;
color: #fff;
padding: 10px 20px;
z-index: 1000; /* Ensures the header stays above other content */
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); /* Optional shadow for better visibility */
}
/* Navigation styles */
.sticky-header-demo nav ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
}
.sticky-header-demo nav ul li {
margin-right: 20px;
}
.sticky-header-demo nav ul li a {
color: #fff;
text-decoration: none;
font-weight: bold;
}
.sticky-header-demo nav ul li a:hover {
text-decoration: underline;
}
/* Section styles for demonstration */
section {
margin-bottom: 100vh; /* Adds enough space for scrolling demonstration */
padding: 20px;
background-color: #f4f4f4;
border: 1px solid #ddd;
border-radius: 5px;
}
3. How It Works
- The
position: sticky;CSS property is applied to the.sticky-headerclass. - The
top: 0;ensures that the header sticks to the top of the viewport when you scroll. - The
z-indexensures that the sticky header remains above other content on the page.
4. Demo Behavior
- Scroll down the page, and the web page header will “stick” to the top of the webpage as you scroll it.
- The header will stay in place, even as the rest of the page content continues to scroll.
5. Notes
- Browser Support: The
position: stickyproperty is supported in most modern browsers. Ensure you test it in your target browsers. - If
position: stickydoesn’t behave as expected, make sure the parent element doesn’t have anoverflow: hiddenoroverflow: autoproperty, as it can interfere with sticky positioning.
Let me know if you need further adjustments!
