我在我的网站上使用bootstrap,我有导航栏固定顶部的问题。当我只是使用常规导航栏时,一切都很好。然而,当我尝试将它切换到导航栏固定顶部时,网站上的所有其他内容都向上移动,就像导航栏不存在一样,导航栏重叠了它。以下是我的基本思路:

.navbar.navbar-fixed-top
  .navbar-inner
    .container
.container
  .row
    //yield content

我试图复制bootstrap的例子,但仍然有这个问题,只有当使用导航栏固定顶部。我做错了什么?


当前回答

之前所有的解决方案都以这样或那样的方式将40像素专门硬编码到html或CSS中。如果导航栏包含不同的字体大小或图像怎么办?如果我有一个很好的理由不把身体衬垫放在第一位呢?我一直在寻找这个问题的解决方案,以下是我想到的:

$(document).ready(function(){
    $('.contentwrap') .css({'margin-top': (($('.navbar-fixed-top').height()) + 1 )+'px'});
    $(window).resize(function(){
        $('.contentwrap') .css({'margin-top': (($('.navbar-fixed-top').height()) + 1 )+'px'});
});

你可以通过调整“1”来上下移动它。它似乎为我工作,无论大小的内容在导航栏,前后调整大小。

我很好奇其他人是怎么想的:请分享你的想法。(顺便说一下,它将被重构,不再重复。)除了使用jQuery,还有其他不使用这种方法的原因吗?我甚至让它与二级导航条一起工作,就像这样:

$('.contentwrap') .css({'margin-top': (($('.navbar-fixed-top').height())
        + $('.admin-nav').height() + 1 )+'px'});

PS:上面是Bootstrap 2.3.2 -它将在3工作。只要泛型类名保持不变…事实上,它应该独立于bootstrap工作,对吧?

编辑:这是一个完整的jquery函数,处理两个堆叠,响应固定导航条的动态大小。它需要3个html类(或者可以使用id): user-top, admin-top和contentwrap:

$(document).ready(function(){

    $('.admin-top').css({'margin-top':($('.user-top').height()+0)+'px'});
    $('.contentwrap') .css({'padding-top': (
        $('.user-top').height()
         + $('.admin-top').height()
         + 0 )+'px'
    });

    $(window).resize(function(){
        $('.admin-top').css({'margin-top':($('.user-top').height()+0)+'px'});
        $('.contentwrap') .css({'padding-top': (
            $('.user-top').height()
             + $('.admin-top').height()
             + 0 )+'px'
        });
});

其他回答

要处理菜单栏中的换行,在导航栏上应用id,如下所示:

<div class="navbar navbar-default navbar-fixed-top" role="navigation" id="topnavbar">

并在包含jquery后在头部添加这个小脚本,像这样:

<script>
    $(document).ready(function(){
        $(document.body).css('padding-top', $('#topnavbar').height() + 10);
        $(window).resize(function(){
            $(document.body).css('padding-top', $('#topnavbar').height() + 10);
        });
    });
</script>

这样,主体的顶部填充就会自动调整。

@Ryan,你是对的,硬编码高度会让它在自定义导航栏的情况下工作得很糟糕。这是我为BS 3.0.0愉快地使用的代码:

$(window).resize(function () { 
   $('body').css('padding-top', parseInt($('#main-navbar').css("height"))+10);
});

$(window).load(function () { 
   $('body').css('padding-top', parseInt($('#main-navbar').css("height"))+10);         
}); 

我只是包装了导航栏在一个

<div width="100%">
<div class="nav-? ??">
...
</nav>
</div>

没有什么花哨的把戏,但它奏效了。

问题在于navbar-fixed-top,它将覆盖你的内容,除非指定主体填充。这里提供的解决方案不能在100%的情况下工作。JQuery解决方案在页面加载后闪烁/移动页面,这看起来很奇怪。

对我来说,真正的解决方案不是使用navbar-fixed-top,而是使用navbar-static-top。

.navbar { margin-bottom:0px;} //for jumtron support, see http://stackoverflow.com/questions/23911242/gap-between-navbar-and-jumbotron

<nav class="navbar navbar-inverse navbar-static-top">
...
</nav>

我把这个放在屈服容器之前:

<div id="fix-for-navbar-fixed-top-spacing" style="height: 42px;">&nbsp;</div>

我喜欢这种方法,因为它记录了需要让它工作的黑客,而且它也适用于移动导航。

编辑-这工作得更好:

@media (min-width: 980px) {
  body {
    padding-top: 60px;
    padding-bottom: 42px;
  }
}