You are on page 1of 1

Code snippet

HTML:

htmlCopy code
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="styles.css"> </head> <body>
<header class="sticky-header"> <nav> <ul> <li><a href="#"> Home </a></li> <li><a href="#"> About </a></li>
<li><a href="#"> Services </a></li> <li><a href="#"> Contact </a></li> </ul> </nav> </header> <!-- Rest of
your website content --> <script src="script.js"></script> </body> </html>

CSS (styles.css):

cssCopy code
/* Styles for the sticky header */ .sticky-header { position : fixed; top : 0 ; width : 100% ; background-color :
#333 ; padding : 10px 0 ; box-shadow : 0px 2px 5px rgba ( 0 , 0 , 0 , 0.1 ); z-index : 1000 ; /* Ensure the header
stays above other content */ } .sticky-header nav ul { list-style : none; margin : 0 ; padding : 0 ; display : flex;
justify-content : center; } .sticky-header nav li { margin : 0 15px ; } .sticky-header nav a { color : #fff ; text-
decoration : none; font-weight : bold; } /* Adjust the padding of the page content to prevent content from being
hidden behind the header */ body { padding-top : 60px ; }

JavaScript (script.js):

javascriptCopy code
// JavaScript to add and remove "sticky" class on scroll window . addEventListener ( "scroll" , function () { var
header = document . querySelector ( ".sticky-header" ); if ( window . pageYOffset > 0 )
{ header. classList . add ( "sticky" ); } else { header. classList . remove ( "sticky" ); } });

In this example, when the user scrolls down the page, the header with class "sticky-header"
becomes fixed to the top using CSS position: fixed; . JavaScript is used to add or remove the
"sticky" class based on the user's scroll position. The CSS for the "sticky" class can be defined to
adjust the header's appearance when it becomes sticky.

You might also like