如何在页面顶部保留导航栏?

Ada*_*cot 8 html css navigation fixed

我正试图让我的导航栏保持在页面的顶部,就像在forbes.com一样

我知道我能做到

nav
{
   position: fixed;
   top: 0;
}
Run Code Online (Sandbox Code Playgroud)

但导航栏不在页面的顶部,它出现在徽标之后......但是当你向下滚动时,我希望导航栏粘在屏幕的顶部.

这是我的网站

mrt*_*gle 5

你可以在JQuery中尝试这样:

HTML:

<div id="wrapper">

    <header>
        <h1>Floater Navigation</h1>
    </header>

    <nav>
        <p>Navigation Content</p>
    </nav>

    <div id="content">
            <p>Lorem Ipsum.</p>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

CSS:

#wrapper {
    width:940px;
    margin: 0 auto;
}

header {
    text-align:center;
    padding:70px 0;
}

nav {
    background: #000000;
    height: 60px;
    width: 960px;
    margin-left: -10px;
    line-height:50px;
    position: relative;
}

#content {
    background: #fff;
    height: 1500px; /* presetting the height */
    box-shadow: 0 0 5px rgba(0,0,0,0.3);
}

.fixed {
    position:fixed;
}
Run Code Online (Sandbox Code Playgroud)

JQuery的:

$(document).ready(function() {

    // Calculate the height of <header>
    // Use outerHeight() instead of height() if have padding
    var aboveHeight = $('header').outerHeight();

    // when scroll
    $(window).scroll(function(){

        // if scrolled down more than the header’s height
        if ($(window).scrollTop() > aboveHeight){

            // if yes, add “fixed” class to the <nav>
            // add padding top to the #content 
            // (value is same as the height of the nav)
            $('nav').addClass('fixed').css('top','0').next().css('padding-top','60px');

        } else {

            // when scroll up or less than aboveHeight,
            // remove the “fixed” class, and the padding-top
            $('nav').removeClass('fixed').next().css('padding-top','0');
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

来源:http://www.jay-han.com/2011/11/10/simple-smart-sticky-navigation-bar-with-jquery/


小智 5

解决方案很简单,在添加px时保持你的CSS

nav
{
   position: fixed;
   top: 0px;
}
Run Code Online (Sandbox Code Playgroud)