LuTz LuTz - 17 days ago 16
CSS Question

Center an element in Bootstrap 4 Navbar

No matter what I try, I can't center something in Bootstrap navbar, any solutions for it?

I've tried adding a div, using

margin:0 auto;
or
margin-right:auto; margin-left:auto;
, used
center-block
class. Nothing works, why is so hard to achieve something so simple I can't understand, what I'm doing wrong?

Here's the current code :

<nav class="navbar navbar-fixed-top navbar-dark main-nav">
<div class="container">
<ul class="nav navbar-nav pull-left">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Download</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Register</a>
</li>
</ul>

<ul class="nav navbar-nav text-center">
<li class="nav-item"><a class="nav-link" href="#">Website Name</a></li>
</ul>

<ul class="nav navbar-nav pull-right">
<li class="nav-item">
<a class="nav-link" href="#">Rates</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Help</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
</div>



Answer

In Bootstrap 4, there is a new utility known as .mx-auto. You just need to specify the width of the centered element.

Ref: http://v4-alpha.getbootstrap.com/components/utilities/#horizontal-centering

Diffferent from Bass Jobsen's answer, which is a relative center to the elements on both ends, the following example is absolute centered.

Here's the HTML:

<nav class="navbar bg-faded">
  <div class="container">
    <ul class="nav navbar-nav pull-sm-left">
      <li class="nav-item">
        <a class="nav-link" href="#">Link 1</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 2</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 3</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 4</a>
      </li>
    </ul>
    <ul class="nav navbar-nav navbar-logo m-x-auto">
      <li class="nav-item">
        <a class="nav-link" href="#">Brand</a>
      </li>
    </ul>
    <ul class="nav navbar-nav pull-sm-right">
      <li class="nav-item">
        <a class="nav-link" href="#">Link 5</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 6</a>
      </li>
    </ul>
  </div>
</nav>

And CSS:

.navbar-logo {
  width: 90px;
}

UPDATE

Bootstrap 4 Alpha 5 changed from .m-x-auto to mx-auto.