OK, first make this change to the media query:
@media screen and (max-width: 782px) {
.admin-bar nav#site-navigation.main-navigation {
position: absolute;
top: 46px;
}
.admin-bar nav#site-navigation.main-navigation.scrolled {
position: fixed;
top: 0;
}
}
Notice that for the first rule inside the media query, the position
property is set to absolute instead of fixed. This allows the menu to scroll with the admin bar, but only at mobile widths (since it’s inside the media query).
The second rule is like the first, but it has a class added to the selector, called scrolled. When the element has that class assigned to it, then the menu bar will be fixed at the top of the screen.
So the only other thing to do is to add some JavaScript to assign the scrolled class to the menu bar after the user has scrolled the window down the same amount of space as the height of the admin bar:
- Install the Header and Footer plugin. This plugin will allow you to add your own script code (this is also useful if you want to add other script code, like the one for Google Analytics, if you want to track how many visitors are coming to your site, and from where).
- Once it’s installed, go to Settings → Header and Footer. In the field labeled Code to be added before the end of the page, copy & paste this script:
<script>
jQuery(document).ready(function($){
// This function gets called with the user has scrolled the window.
$(window).scroll(function () {
if ($(this).scrollTop() > 46)
{
// Add the scrolled class to those elements that you want changed
$("#site-navigation").addClass("scrolled");
}
else
{
$("#site-navigation").removeClass("scrolled");
}
});
});
</script>
What this function does is to detect when the window has been scrolled more than 46px. If it has, then it adds the scrolled class to the menu. If the window has been scrolled less than 46px, then the scrolled class is removed.
One other addition you may want to make in your CSS. You might notice that when you hover over the admin bar, the menu items from the admin bar are hidden behind the nav menu. Add this rule so that the admin menu items show up in front:
#wpadminbar {
z-index: 100001;
}