I am trying to find a solution to a problem that I have encountered while trying to get a fixed-top navigation menu to work dynamically in W3.CSS. By dynamically, I mean that the horizontally-orientated navigation bar should remain in its place under the page title and image until the page is scrolled downwards and reaches the top of the viewport. At this point, it should fix itself to the top of the screen.
I have been able to achieve this effect using my own html/css and jquery script but this method doesn’t work as intended with W3.CSS. I have been moving my websites over to W3.CSS as I as a means of making them responsive and also because css is not my strong point and I like the W3.CSS structure.
The menu bar operates as it should when it is in its static mode but, when it is fixed, which involves position:absolute and a z-index of 1, the dropdown menus no longer appear above the bar but are concealed within it. I have tried altering the z-index values of the dropdown-hover and dropdown-content elements but cannot find a solution to this problem. If there is anyone who can, I would be very grateful.
The html code below is based closely on the “Navigation Bar with Dropdown” example taken from the W3.CSS Navigation Bars page. I also include the css used to fix the bar and the jquery function to call the css once the top of the screen is reached.
HTML
<div id=”container”>
<div id=”header”></div>
<img id="header_image" src="titleimage.jpg" alt="Header Image" class="header_image"/>
<img id="header_image_m" src="title_image_m.jpg" alt="Header Image" class="header_image"/>
<div id=”nav_bar_container>
<div id=”nav_bar” class="w3-bar w3-light-grey">
<a href="#" class="w3-bar-item w3-button w3-mobile">Home</a>
<a href="#" class="w3-bar-item w3-button w3-mobile">Link 1</a>
<div class="w3-dropdown-hover">
<button class="w3-button">Dropdown</button>
<div class="w3-dropdown-content w3-bar-block w3-card-4 w3-mobile">
<a href="#" class="w3-bar-item w3-button">Link 1</a>
<a href="#" class="w3-bar-item w3-button">Link 2</a>
<a href="#" class="w3-bar-item w3-button">Link 3</a>
</div>
</div>
</div>
</div>
CSS
#nav_bar_container, #nav_bar{
margin:0;
padding:0;
width:100%;
max-width:948px;
}
.nav_bar_fixed {
position:fixed;
top:0px;
z-index:1;
}
Jquery
if ($( window ).width() > 600) {
$(window).scroll(function() {
var fixedBar = $('#nav_bar'),
targetScroll = $('#nav_bar_container').position().top,
currentScroll = $('html').scrollTop() || $('body').scrollTop();
fixedBar.toggleClass('nav_bar_fixed', currentScroll >= targetScroll);
});
}