Search code examples
htmlcssalignmentcenterflexbox

How to center content in a flexbox


I'm having an issue on my project where the content is not aligning vertically in the flexbox. We have a fluid responsive page that needs to center all items within the flexbox via %'s. in the example below we've set a fixed pixel height just so you can play with it.

I have tried a ton of different methods for hours..

body{
  margin:0px auto;

}
/* top bar navigation */
.topBoxNav {
  background:red;
  padding: 0;
  list-style: none;
  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;
  width: 100%;
  height: 50px;
  color: white;
  font-weight: bold;
  font-family: 'League Gothic';
  font-size: 1.5em;
  text-align: center;
}

.topBoxNav li {
  box-sizing: border-box;
  border: 1px solid white;
  width: 100%;
  height: 100%;
}

.topBoxNav a {
  text-decoration: none;
  color: white;
}

HTML:

<nav class="" alt="top Nav">
  <ul class="topBoxNav">
    <li><a href="">Box1</a></li>
    <li><a href="">Box2</a></li>
    <li><a href="">Box3</a></li>
  </ul>     
</nav>

example:

http://codepen.io/anon/pen/iwDdy


Solution

  • First, realize that the one that has the display: flex property is your ul, not your li elements, so you have two options here:

    1) Give your li elements display: flex and add align-items: center to it and justify-content: center

    You will get something like this:

    .topBoxNav li {
      box-sizing: border-box;
      border: 1px solid white;
      width: 100%;
      height: 100%;
    
      display: flex;
    
      align-items center
      -moz-align-items center
      -ms-flex-align center
      -webkit-align-items center
    
      justify-content center
      -moz-justify-content center
      -ms-flex-pack center
      -webkit-justify-content center
    }
    

    2) Give your li elements line-height equal to the height, in this case 50px and vertical-align: middle.

    You will have something like this:

    .topBoxNav li {
      box-sizing: border-box;
      border: 1px solid white;
      width: 100%;
      height: 100%;
      align-items: center;
      -webkit-align-items: center;
      vertical-align: middle;
      line-height: 50px;
    }
    

    Both ways will work :)