一尘不染

如何在Bootstrap中将导航项居中?

css

如果我想根据
Bootstrap 4中浏览器窗口的大小将导航项(链接)放在导航栏中,该怎么办?请看一下代码:

<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Navbar</a>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
        <div class="navbar-nav">
            <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
            <a class="nav-item nav-link" href="#">Features</a>
            <a class="nav-item nav-link" href="#">Pricing</a>
            <a class="nav-item nav-link disabled" href="#">Disabled</a>
        </div>
    </div>
</nav>

现在,我想根据浏览器的宽度将div“ navbar-nav”居中。我尝试过的一件事是给它mr-auto和ml-auto,它的确使它居中,但不完全准确。实际上,它根据宽度“浏览器窗口宽度-徽标宽度”将其居中。我希望它恰好位于屏幕中间。

我也尝试过将位置更改为绝对位置,但是同样,在折叠模式下,这种布局也会变得混乱。


阅读 344

收藏
2020-05-16

共1个答案

一尘不染

快速使用flexbox和margin utils…中心品牌和链接

<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="d-md-flex d-block flex-row mx-md-auto mx-0">
        <a class="navbar-brand" href="#">Navbar</a>
        <div class="collapse navbar-collapse mr-auto" id="navbarNavAltMarkup">
            <div class="navbar-nav">
                <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
                <a class="nav-item nav-link" href="#">Features</a>
                <a class="nav-item nav-link" href="#">Pricing</a>
                <a class="nav-item nav-link disabled" href="#">Disabled</a>
            </div>
        </div>
    </div>
</nav>

Bootstrap 4.1 中心品牌,在移动设备上向左对齐

EDIT..

答案仍然基本相同。使用mx-auto到中心。

<nav class="navbar navbar-toggleable-md navbar-light bg-faded">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Navbar</a>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
        <div class="navbar-nav mx-auto">
            <a class="nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
            <a class="nav-link" href="#">Features</a>
            <a class="nav-link" href="#">Pricing</a>
            <a class="nav-link disabled" href="#">Disabled</a>
        </div>
    </div>
</nav>
2020-05-16