如何将导航固定到滚动中心?

How fixed a navigation to the center on scroll?

我有一个以 80% 宽度居中的导航,当我滚动页面时,在某个时间点我将 header 固定到顶部,当我这样做时它浮动到左侧而不是留在中间。如何让导航居中固定在顶部

html

<div id="foo">
</div>
<div id="nav">
</div>
<div id="bar">
</div>

css

#foo{
    height:100px;
    width:100%;
}
#bar{
    height:1000px;
    width:100%;
}

#nav{
    width: 80%;
    height: 100px;
    margin: 0 auto;
    background-color: #FFCC00;
}
.fixed-nav{
    position: fixed;
    top: 0;
}

脚本

var bottom = $('#nav').offset().top;
$(window).scroll(function(){    
    if ($(this).scrollTop() > bottom){ 
        $('#nav').addClass('fixed-nav'); 
    }
    else{
        $('#nav').removeClass('fixed-nav');
    }
});

这是我在 jsfiddle

中的代码

您需要以另一种方式使导航居中。如果您设置了固定的 width(在本例中为 80%),您可以简单地使用 margin-left: 10%; 而不是 margin: 0 auto;.

DEMO

注意:我也设置了body{ margin: 0; }可以正常工作。

left: 10% 添加到 .fixed-nav 可以解决这个问题。此外,您需要在 CSS 中添加 body { margin: 0px; } 否则 #nav 在向下滚动时会变大。

这是编辑后的 ​​jsfiddle