Em units versus ex units

From MozillaZine Knowledge Base
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

This article addresses the use of relative "em" and "ex" units in CSS, which can potentially cause rendering problems due to pixel rounding errors. Read about em and ex values in the CSS2 specification.

The Problem

The problem occurs when a relative value doesn't equal a whole pixel value. In that case, the Gecko layout engine can sometimes incorrectly add or remove a pixel from an object's size due to rounding errors. Rounding errors can occur in circumstances not covered by this article as well. A lot of information on the topic is available in Mozilla's Bugzilla bug-tracking database [1].

The Solution

Though the problem can be avoided altogether by using absolute pixel units to define the size of your objects, sometimes relative units are necessary. Therefore, relative values must be intelligently used to avoid the problem. At "normal" font sizes (the defaults on Windows systems, and possibly Linux and others), 1 em is 10.06667 pixels, and 1 ex is 6 pixels. Therefore, ex units are recommended over em units, since they are more easily converted into evenly-rounding pixel values. Though some relative values may scale cleanly to different font sizes, there is, once again, potential for rounding errors. Regardless, it's still safer and easier to calculate whole pixel values using ex units.

The DOM Inspector can be used to find the calculated pixel value of objects sized using relative units [2].

In the following table, notice how much easier it is to get evenly-rounded pixels using exes. Most whole pixel values fall on common fractions of ex units (1/2, 1/3, 1/6). By contrast, a single em unit rounds to 10.06667 pixels, and the first whole pixel value is obtained at 3 ems. Additionally, odd fractions are needed to reach useful whole pixel values when using ems. With exes, it's simply a matter of dividing by six.

em pixels ex pixels
.093em 1px
.17ex 1px
.19em 2px
.25em 2.66667px .25ex 1.53333px
.28em 3px
.3em 3.2px .3ex 1.8px
.33em 3.53333px .33ex 2px
.47em 5px
.5em 5.33333px .5ex 3px
.67em 7.13333px .67ex 4px
.75em 8px .75ex 4.53333px
.83ex 5px
1em 10.06667px 1ex 6px
1.5em 16px 1.5ex 9px
2em 21.3333px 2ex 12px
2.5em 26.6667px 2.5ex 15px
2.67ex 16px
3em 32px 3ex 18px
3.5em 37.3333px 3.5ex 21px
4em 42.6667px 4ex 24px
4.5em 48px 4.5ex 27px
5em 53.3333px 5ex 30px
5.33ex 32px
8ex 48px
10em 106.667px 10ex 60px
Relative units converted to pixels