HTML:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Sticky Header Example</title> <link rel="stylesheet" href="styles.css"> </head> <body> <header class="sticky-header"> <!-- Your header content goes here --> <h1>Sticky Header</h1> </header> <!-- Rest of your webpage content --> <div class="content"> <!-- Your webpage content goes here --> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </div> <script src="script.js"></script> </body> </html>
CSS (styles.css):
.sticky-header { position: fixed; top: 0; width: 100%; background-color: #333; padding: 10px 0; text-align: center; color: #fff; } .content { /* Add margin top to compensate for the fixed header */ margin-top: 60px; /* Adjust this value based on your header's height */ }
JavaScript (script.js):
window.onscroll = function() {stickyHeader()}; var header = document.querySelector(".sticky-header"); var sticky = header.offsetTop; function stickyHeader() { if (window.pageYOffset > sticky) { header.classList.add("sticky"); } else { header.classList.remove("sticky"); } }
In this code:
- The HTML structure contains a header with the class "sticky-header" and the rest of the webpage content wrapped in a div with the class "content".
- CSS is used to style the header and create the sticky effect by setting its position to fixed when the user scrolls past it.
- JavaScript is used to add/remove the "sticky" class to the header based on the user's scroll position. This class contains the styles to make the header stick to the top of the page.
0 on: " How you can create a sticky header for a website using CSS and JavaScript."