Vertical Align A Horizontal Menu in CSS

This is just a quick post on vertically aligning a horizontal menu with CSS. There are many posts out there on how to do this, but on a current project, I found that none of the tutorials I found worked. I managed to stumble upon a way that worked. I know for many this will be common sense....this post is for everybody else.

Requirements

  • Horizontal menu of a fixed height
  • Elements of a fixed width
  • Text within these elements may be one or two lines
  • All text must be vertically aligned to the middle

If this whole menu was only one line, then a simple line-height and vertical-align would have been the solution, but since there can be more than one line, this would not work.

Instead I needed to go back a few years to the world of tables. Now before anyone jumps all over that, I didn't actually use tables. Instead I used the CSS property "display" to treat the links like table cells. The way tables vertically align content within them is exactly how I wanted these links to be treated to this was a good solution.

So on with the code. The HTML we'll work with is below:

<div id="site-menu">
  <ul class="links primary-links">
    <li><a title="item 1" href="#">Item 1</a></li>
    <li><a title="item 2" href="#">Item 2</a></li>
    <li><a title="item 3" href="#">This is a two line link</a></li>
    <li><a title="item 4" href="#">Item 4</a></li>
  </ul>
</div>

The CSS for these links is as follows

#site-menu {
  height: 100px;
}

.primary-links {
  text-align: center;
}

.primary-links li {
  width: 100px;
  white-space: normal;
  float: left;
}

So with what's there right now you will have a horizontal list of links which are all vertically aligned to the top. The desired result we want is to have them all vertically aligned middle. I had attempted to treat the list elements as table cells but this had no effect. On a whim I decided to throw the table cell CSS onto the anchor tags instead.

.primary-links a {
  display: table-cell;
  height: 100px;
  vertical-align: middle;
}

To my surprise this worked like desired. I got a horizontal list of links which were vertically aligned to the middle. A height must be given to the anchor tag in order for this to work.

Summary

So once again my requirements were to have a horizontal menu of a fixed height, who's elements were a fixed width. The text within these elements may be one or two lines and they all must be vertically aligned to the middle. If you have similar requirements to myself I hope I just saved you some time. If anyone has suggestions and or links to other ways to do this, please sound off in the comments below.

Do you have a bullet proof way of horizontally aligning links that you rely on? If so share below! I'm very interested to know how others have approached this.

More content from: