skip to Main Content

I am terrible at CSS so I am having trouble centering my <li> (navbar pills) vertically for my navbar. This navbar is from twitter bootstrap

Here is the HTML for my navbar:

  <div class="container">
    <nav class="navbar navbar-default navbar-fixed-top">
      <ul id="nav_pills" class="nav nav-pills" role="tablist">
        <li role="presentation">
          <a href="/">About</a>
        </li>
        <li role="presentation">
          <a href="/gallery">Gallery</a>
        </li>
        <li role="presentation">
          <a href="/news">News</a>
        </li>
        <li role="presentation">
          <a href="#history">History</a>
        </li>
        <li role="presentation">
          <a href="#contact">Contact</a>
        </li>
      </ul>
    </nav>
  </div>

My navbar currently looks like so:

enter image description here

I am trying to use flexbox as well because while browsing for solutions, using flexbox seems to be an easy way to center my navbar buttons vertically.

This is what I have currently tried but it isn’t working =/

.nav li {
    display: flex;
    flex-direction: row;
    align-items: baseline;
}

2

Answers


  1. To vertically align it, set a line height for the list elements which is equal to the navbar height and remove the top and bottom padding. It won’t need Flexbox at all 🙂

    .nav > li > a {
        display: block;
        line-height: 50px; // Add
        padding: 0 15px; // Modify
        position: relative;
    }
    

    Bootply

    Login or Signup to reply.
  2. Set display: flex for the <ul class="nav">, not for items.
    Also use align-items: center for vertical aligment:

    .nav {
      height: 70px;
      
      display: flex;
      justify-content: center;
      align-items: center;
    }
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="container">
        <nav class="navbar navbar-default navbar-fixed-top">
          <ul id="nav_pills" class="nav nav-pills" role="tablist">
            <li role="presentation">
              <a href="/">About</a>
            </li>
            <li role="presentation">
              <a href="/gallery">Gallery</a>
            </li>
            <li role="presentation">
              <a href="/news">News</a>
            </li>
            <li role="presentation">
              <a href="#history">History</a>
            </li>
            <li role="presentation">
              <a href="#contact">Contact</a>
            </li>
          </ul>
        </nav>
      </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search