Vertical align for navigation lists with multiple lines

Last updated: 2005/12/02

Return to the main page

Let's see a quick tip for aligning vertically navigation lists that use the tipical floated box approach to display the list in a row, but that have several items displayed across multiples lines.

Suppose that we have this CSS code for our single-line navigation list:

#nav li {
  display: block;
  height: 3em;
  margin: 0 3px;
  padding: 3px 7px;
  background: Khaki;
  float: left;
}

that applies to this HTML code:

<ul id="nav">
  <li><a href="link1.html">Item one</a></li>
  <li><a href="link2.html">Item two</a></li>
  <li><a href="link3.html">Large third<br>item</a></li>
  <li><a href="link4.html">The Fourth</a></li>
  <li><a href="link5.html">Very large<br>fifth item</a></li>
</ul>

and we need to modify it for aligning vertically items that have both single and multiple lines. At first sight, the logical approach is using the vertical-align attribute. Since this attribute only applies to inline elements, we add it to the a tag inside the list items:

#nav li a { vertical-align: middle; }

But as usually, this attribute does nothing for us:


The problem is that vertical-align centers vertically the inline elements, but relative to the tallest element in each line. Since inside each li the tallest (and only) element is the a tag, the whole line is positioned at the top the block.

But there is another attribute that is here to save the day: line-height. If the line height of the block is equal to its height, the inline tags inside the block that have only a line are centered vertically. But there are also some blocks with multiple lines inside, so we need to set the line height of those blocks to height_of_block / number_of_lines, so the added height of the lines is equal to the block height.

In our example we have blocks with two lines, so we need to set the line-height of those elements to half the height of the block. To differentiate those lines, we'll mark it with a special class. The new code for this would be something like this:

CSS

#nav-fixed li {
  display: block;
  height: 3em;
  margin: 0 3px;
  padding: 3px 7px;
  background: Khaki;
  float: left;
  text-align: center;
  line-height: 3em;
}

#nav-fixed .double-line {
  line-height: 1.5em;
}

HTML

<ul id="nav-fixed">
  <li><a href="link1.html">Item one</a></li>
  <li><a href="link2.html">Item two</a></li>
  <li class="double-line"><a href="link3.html">Large third<br>item</a></li>
  <li><a href="link4.html">The Fourth</a></li>
  <li class="double-line"><a href="link5.html">Very large<br>fifth item</a></li>
</ul>

And here it's the desired result:


This have been tested in Firefox, IE 5 & 6, Opera 7 & 8 and Konqueror 3.2.

Return to the main page