How to lock text vertically with CSS
When I create a web site I always take a look on it when increasing the text size to 125% in the browser. This is to ensure that the site also looks ok for my grand mother and other people who, for example, is a visually impaired. If the design is quite simple it usually looks good. However if it’s a more complex design with for example a horizontal meny with a defined height, the text usually becomes misaligned vertically (and sometimes push following content down so the design breaks). Usually this doesn’t matter, but it can be a bit annoying, so to avoid this I use the following technique.
Note that this technique is only working on non-wrapped text. It is also obsolete in some newer browsers with zoom capability.
First I’ll demonstrate the common way to vertically align text. Then I’ll show you how to do it my way.
Let’s start out with some html. This is a simple example with an unordered list that we’ll use as a menu:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example</title>
<style type="text/css" media="screen">
</style>
</head>
<body>
<ul id="menu">
<li><a href="#">Menuitem 1</a></li>
<li><a href="#">Menuitem 2</a></li>
<li><a href="#">Menuitem 3</a></li>
</ul>
</body>
</html>
We’ll then apply some basic CSS to add some basic formatting and make the menu horizontal, have a background color and a height:
* { margin: 0; padding: 0; }
body {
font: 76%/175% Verdana, Tahoma, sans-serif;
background: #fff;
}
#menu {
background: #222;
height: 30px;
overflow: hidden;
}
#menu a {
float: left;
color: #eee;
padding: 0 10px;
line-height: 30px;
}
Setting the line-height on #menu a to the same value as the height on #menu is a quite common way to vertically align text. So far the menu looks like this (there is also a live example):
![]()
But this is what happens if we increase the font size to 125% in Firefox:
![]()
The text is vertically misaligned. Not so neat. Let’s fix it by changing our CSS a bit:
#menu a {
float: left;
color: #eee;
padding: 14px 10px 15px;
height: 1px;
line-height: 1px;
}
As you can see, I changed the line-height and height to 1px and “substituted” them for some padding on the top and bottom. Now the vertical alignment is fixed even if you increase the font size (see live example 2).



