html – 如何使用Flexbox在Bootstrap 4中居导航栏

好吧,我想实现这个目标:
https://i.imgur.com/BDM7JvD.jpg使用Bootstrap 4 Navbar.

如何使用flexbox或mr-auto etc实用程序将导航链接/项目集中在视口中间.我试图避免基于CSS的定位方法,因为它可能会在不同的设备上查看.但是,如果CSS方法承诺处于同一集中位置,那么为什么不呢!

注意:一些人可能会说使用justify实用程序,舞会是你不能使用它们作为navbar品牌和navbar-nav不能包装在div内.如果我这样做,布局就会混乱.

nav class =“navbar navbar-toggleable-md navbar-light bg-custom card-shadow-bottom”>

        <div class="container">

            <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>

            <a class="navbar-brand" href="#"><img src="img/nav-logo.png" alt="logo" class="nav-logo"></a>

            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                <ul class="navbar-nav ml-auto mr-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="#">Home</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Disabled</a>
                    </li>
                </ul>
            </div>

        </div>

    </nav>

最佳答案 使用flexbox实用程序以您希望的方式对齐组件.这里,justify-content-center用于使navbar-nav居中.

<nav class="navbar navbar-fixed-top navbar-toggleable-sm navbar-inverse bg-primary justify-content-between">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#collapsingNavbar">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a href="/" class="navbar-brand">Brand</a>
    <div class="navbar-collapse collapse justify-content-center" id="collapsingNavbar">
        <ul class="navbar-nav">
            <li class="nav-item active">
                <a class="nav-link" href="#">Link <span class="sr-only">Home</span></a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-toggle="collapse">Link</a>
            </li>
        </ul>

    </div>
    <ul class="nav navbar-nav flex-row">
        <li class="nav-item"><a class="nav-link pr-3" href=""><i class="fa fa-facebook"></i></a></li>
        <li class="nav-item"><a class="nav-link" href=""><i class="fa fa-twitter"></i></a></li>
    </ul>
</nav>

More Navbar alignment examples

更新Bootstrap 4.0.0

navbar-toggleable-sm现在是navbar-expand-md
navbar-inverse现在是navbar-dark
navbar-fixed-top现在是固定顶部

点赞