将Bootstrap导航对齐到中心

时间:2014-02-24 06:43:40

标签: css twitter-bootstrap twitter-bootstrap-3

我遇到了bootstrap 3导航的问题,我在左侧,中间和右侧都有一些内容。似乎没有选项可以使导航居中。

http://jsfiddle.net/29tQt/embedded/result/

我正在尝试将名为“center”的链接放在页面的中心,我该如何实现?

<nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span>
 <span class="icon-bar"></span>
 <span class="icon-bar"></span>
 <span class="icon-bar"></span>

            </button> <a class="navbar-brand" href="#">Brand</a>

        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li class="active"><a href="#">Center</a>
                </li>
                <li><a href="#">Center</a>
                </li>
                <li><a href="#">Center</a>
                </li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">Right</a>
                </li>
                <li><a href="#">Right</a>
                </li>
            </ul>
        </div>
    </div>
</nav>

4 个答案:

答案 0 :(得分:55)

谢谢大家的帮助,我添加了这段代码,似乎解决了这个问题:

.navbar .navbar-nav {
    display: inline-block;
    float: none;
}

.navbar .navbar-collapse {
    text-align: center;
}

<强>来源

Center content in responsive bootstrap navbar

答案 1 :(得分:5)

将'justified'类添加到'ul'。

<ul class="nav navbar-nav justified">

CSS:

.justified {
    position:absolute;
    left:50%;
}

现在,计算其'margin-left'以便将其与center对齐。

// calculating margin-left to align it to center;
var width = $('.justified').width();
$('.justified').css('margin-left', '-' + (width / 2)+'px');

JSFiddle Code

JSFiddle Embedded Link

答案 2 :(得分:1)

.navbar-nav {
   float: left;
   margin: 0;
   margin-left: 40%;
}

.navbar-nav.navbar-right:last-child {
   margin-right: -15px;
   margin-left: 0;
}

Updated Fiddle

由于您使用了float属性,除了手动调整外,我们没有太多选项。

答案 3 :(得分:0)

试试这个css

.clearfix:before, .clearfix:after, .container:before, .container:after, .container-fluid:before, .container-fluid:after, .row:before, .row:after, .form-horizontal .form-group:before, .form-horizontal .form-group:after, .btn-toolbar:before, .btn-toolbar:after, .btn-group-vertical > .btn-group:before, .btn-group-vertical > .btn-group:after, .nav:before, .nav:after, .navbar:before, .navbar:after, .navbar-header:before, .navbar-header:after, .navbar-collapse:before, .navbar-collapse:after, .pager:before, .pager:after, .panel-body:before, .panel-body:after, .modal-footer:before, .modal-footer:after {
    content: " ";
    display: table-cell;
}

ul.nav {
    float: none;
    margin-bottom: 0;
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    width: 240px;
}