Sticky Header for Mobile
This will stick the header/nav to the top of the screen as mobile users scroll up and down the page:
// For smaller screens
@media (max-width: 768px) {
// Pins the header to the top of the page
#page-header {
position: sticky;
top: 0;
z-index: 1000;
}
// Pins the nav bar to the top of the page
#page-navigation {
position: sticky;
z-index: 999;
}
}
Since the navbar isn't in the same container as the header, you'd need to adjust the position of the nav to be directly below the header to keep everything aligned properly. Insert this code in the script section of the advanced editor to dynamically adjust the nav:
document.addEventListener("DOMContentLoaded", function() {
// Grabbing header and nav elements
const header = document.getElementById('page-header');
const nav = document.getElementById('page-navigation');
function updateNavPosition() {
// Will only trigger if screen size matches the media query
const isMobile = window.matchMedia('(max-width: 768px)').matches;
if (isMobile) {
// Capturing header height
const headerHeight = header.offsetHeight;
// Adjusting nav to be right below header
nav.style.top = `${headerHeight}px`
} else {
// Reset nav position if not on mobile screen
nav.style.top = null;
}
}
updateNavPosition();
// Runs the function each time the screen is resized for responsive behavior
window.addEventListener('resize', updateNavPosition);
});
Use this CSS code to apply this functionality to Amplify homepages