I have been tasked with developing a webpage featuring a prominent header at the top of the page. This header will include the navigation bar, logo, and website title. As the user begins to scroll, I want the header to transform into a compact version that only displays the navigation bar, which will remain fixed at the top of the page while scrolling. I couldn't find any resources online on how to achieve this transition, so I thought it would be interesting to explore this challenge for myself as well as others.
Below is the CSS code for the initial large header:
<style>
header {
background-color: #0097A7;
color: #ffffff;
padding: 2%;
text-align: center;
}
h1 {
font-size: 270%;
margin: 2% 0;
}
nav {
background-color: rgba( 255, 255, 255, .4);
border-radius: 25px;
width: 50%;
margin-left: auto;
margin-right: auto;
font-family: 'Neuton', serif;
font-weight: bold;
}
nav a {
color: #fff;
display :inline-block;
font-size: 100%;
font-weight: bold;
padding: 1% 4%;
}
nav a:hover {
background-color: rgba( 255, 255, 255, .4);
box-sizing: border-box;
border-radius: 25px;
}
</style>
<header>
<h1><img alt="Logo" class="logo" height="50" src="media/logo.png">
Fish & Chips </h1>
<nav>
<a href="index.php">Home</a>
<a href="gallery.php">Gallery</a>
<a href="about.php">About Us</a>
<a href="contact.php">Contact Us</a>
</nav>
</header>
This is the smaller header design I aim to switch to:
<header>
<nav>
<a href="index.php">Home</a>
<a href="gallery.php">Gallery</a>
<a href="about.php">About Us</a>
<a href="contact.php">Contact Us</a>
</nav>
</header>
Here's the code snippet I discovered online to fix the header at the top of the screen:
<style>
nav {
position:fixed;
top:0px;
}
</style>
I am uncertain about how to implement the transition between these two headers. I assume it may involve a simple jQuery script like the one below:
if (xPos > 0){
switch to small, fixed header
} else{
switch to large header
}
Where xPos indicates how far down the page the user has scrolled. However, I haven't found a clear solution for this process yet.