darkginger darkginger - 17 days ago 5
CSS Question

Correcting vertical alignment of navbar link in Bootstrap 4

I am running into a weird issue with Bootstrap 4's

.navbar
class in my Rails application.

In short, I am making a navbar, and I am trying to add a link on the right side. According to the documentation, the
.pull-**-right
class should work within the navbar and put the link on the right side.

Now it successfully does that; however, the vertical alignment is off (even though the
navbar-brand
link on the left is perfect):

<nav class="navbar navbar-full navbar-light" style="background-color: #002b52">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<%= link_to "Example", root_path, class: "navbar-brand" %>
<%= link_to "About Us", about_path, class: "pull-sm-right navlink" %>
</nav>
</div>
</nav>


It didn't work originally, so I made up the
.navlink
class and added some CSS with:

.navlink {
vertical-align: middle;
}


Even after doing so, the right link isn't centered vertically (it's close to the top) even though the
navbar-brand
is with no extra CSS magic.

Any ideas on why this is happening?

Answer

Seems like you're mixing Bootstrap v3 classes with v4 while not using the default navigation structure found in the documentation, particularly this: see Nav. And the class navbar-header doesn't exist in v4.

Hopefully this helps.

Basic Setup

.navbar
  a.navbar-brand
  ul.nav.navbar-nav
    li.navbar-item
      a.nav-link

Rails Example:

<nav class="navbar navbar-full navbar-light">

  <%= link_to "Example", root_path, class: "navbar-brand" %>

  <ul class="nav navbar-nav">
    <li class="nav-item pull-sm-right">
      <%= link_to "About Us", about_path, class: "nav-link" %>
    </li>
  </ul>

</nav>

Working Example:

.navbar {
  background-color: #002b52;
}
.navbar .navbar-nav li > .nav-link,
.navbar a.navbar-brand {
  color: white;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar navbar-full navbar-light">

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

  <ul class="nav navbar-nav">
    <li class="nav-item pull-sm-right">
      <a class="nav-link" href="#">About Us </a>
    </li>
  </ul>

</nav>