How can I make a fix positioned menu bar?

时光毁灭记忆、已成空白 提交于 2019-12-30 10:10:04

问题


I would like to style my menu bar Like THIS. It's fixed to the top of the site when you scroll down and it isn't fixed where it is when the page is loaded.

How can it be done with CSS?


回答1:


What you're after is a 'sticky navbar/menu'.

The simplest way would be to add the below CSS to your menu/navbar

position:fixed;
top:0px;

That said, for an effect closer to the one you've posted, you'll probably want to look at using some jQuery, e.g.:

$(window).bind('scroll', function() {
     if ($(window).scrollTop() > 50) {
         $('.menu').addClass('fixed');
     }
     else {
         $('.menu').removeClass('fixed');
     }
});

What this does is 'fix' the menu bar to the top of the page once you scroll past a certain point (e.g. 50px) by adding the CSS class 'fixed' to the .menu element, the fixed class would simply be e.g. the CSS above.

There are some nice examples listed here.




回答2:


Source: Creating a sticky nav css and jquery

HTML

<div id="menu">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Blog</a></li>
        <li><a href="#">Shop</a></li>
        <li><a href="#">Contact</a></li>
    </ul>
</div>
<div id="content">
This is some content 0<br/>
This is some content 1<br/>
This is some content 2<br/>
This is some content 3<br/>
This is some content 4<br/>
This is some content 5<br/>
This is some content 6<br/>
This is some content 7<br/>
This is some content 8<br/>
<div id="data" />
</div>

CSS

* {
    font-family: Consolas,Sans-serif;
    font-size: 10pt;
}
#menu {
    position: absolute;
    width: 100%;
}
#menu.out {
    position: fixed;
}
#menu ul {
    margin: 0;
    padding: 1em .5em;
    list-style: none;
    background-color: #fc9;
}
#menu ul li {
    display: inline-block;
}
#menu ul li a {
    padding: 5px .5em;
}
#content {
    background-color: #ebebee;           
    padding: 4em 1em 1em;
    height: 900px;
}

JQuery:

    var menu = $("#menu");
var ul = menu.find("ul");
var content = $("#content")[0];
var data = $("#data");
var menuHeight = menu[0].getBoundingClientRect().bottom;
var inView= true;

$(document).scroll(function(evt) {
    evt.preventDefault();
    var top = content.getBoundingClientRect().top;
    var nextInView = top+menuHeight > 0;

    if (inView ^ nextInView)
    {
        data.append("<div>Switching.</div>")
        inView = nextInView;
        if (inView)
        {
            menu.removeClass("out");
        }
        else
        {
            menu.addClass("out");
            ul.hide().slideDown("fast");
        }
    }
});

Fiddle :Demo

Courtesy : Robert Koritnik

Hope this helps

Happy Coding



来源:https://stackoverflow.com/questions/20630848/how-can-i-make-a-fix-positioned-menu-bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!