html5 – How can I align some components of a bootstrap3 navbar to the left and others to the right?

Question:

Starting from a standard Bootstrap navbar need some buttons or links to be aligned to the left, others to the center (for example: our brand icon) and others to the right.

This was the first thing I tried to do:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>    
  </div>
  <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
      <li class="navbar-left"><a href="#">Izquierda 1</a></li>
      <li class="navbar-left"><a href="#">Izquierda 2</a></li>
      <li class="active"><a href="#">Center 1</a></li>
      <li><a href="#">Center</a></li>
      <li class="navbar-right"><a href="#">Derecha 1</a></li>
      <li class="navbar-right"><a href="#">Derecha 2</a></li>
    </ul>
  </div>
</nav>

Looking in the documentation for Bootstrap 3 I didn't find any examples or ideas of how to achieve this. How could it be done?

Answer:

A solution without needing to modify your html structure is to use .pull-right if the li goes to the right and .pull-left if it goes to the left and placing this script:

  .navbar-nav {
    width: 100%;
    text-align: center;

  }

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

Which allows us to start with all the <li> centered and then pull them to the right and / or left what we need.

The final HTML would look like this:

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>    
  </div>
  <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
      <li class="pull-left"><a href="#">Izquierda 1</a></li>
      <li class="pull-left"><a href="#">Izquierda 2</a></li>
      <li class="active"><a href="#">Center 1</a></li>
      <li><a href="#">Center</a></li>
      <li class="pull-right"><a href="#">Derecha 1</a></li>
      <li class="pull-right"><a href="#">Derecha 2</a></li>
    </ul>
  </div>
</nav>

Live example

Scroll to Top