How to use the EM unit in CSS

Everybody on the web agree, that dynamic and scalable font size are the way to go. And this is where the .em unit is perfect.

The em unit is recommended by the W3C

Calculating pixel to em.

On a standard system 1 em equals 16 pixel. The means 1 pixel equals 1:16 = 0,0625 em. So if you need a font size of 12 pixel, you would calculate 0.0625 x 12 = 0,75 em.

Em and inheritance

The em unit set on a <tag> is inherited by <tags> under it in the DOM tree.
An example:

 
<div style="font-size:1.1em;">
<div>text</div>
</div>
 

The text inherits the font size from the div above it.
This is standard CSS inheritance

The fun part starts when we have 2 em definitions in the tree, like:

 
<div style="font-size:1.1em;">
<div style="font-size:1.3em;">text</div>
</div>
 

You would think the text now would have a size of 1.3em, but this is not the case. The ems are multiplied with each other, so the size is actually 1.1 x 1.3 = 1,43 em.

This is the reason it's bad practice to put em sizes on <tags> that can be inside its own tag, like <div>, <td>, <li>.

Example, if you wanted a 0.8em size on your list, this would be a bad way to do it:

 
li { font-size:0.8em }
 

This would make a list like this having smaller and smaller text:

 
<ul>
<li>List item 1</li>
<li>
<ul>
<li>sub list item 1</li>
</ul>
</li>
</ul>
 

The "sub list item 1" would have a size of 0,64 em.

So the right way would be setting a class on the first <ul> with a font-size, and it will be inherited to the rest of the list.

IE have some inheritance issues. For some wierd reason, <td>, <input> , <button> , <textarea> and <select> are not following the standard inheritance rules. They just stop the inheritance. Example, if you set a 0.8em font-size on the body, it will still be 1.0 em on those tags. To hack this, you can set a 1.0em font-size on those tags. This will make IE calculate the font-size: 0.8em x 1.0em = 0.8em.

Another wierd issue IE has, is not showing the correct size with em units. It shows them either too big or too small. The hack for this is setting 100% font-size on the HTML tag.

Complete IE hack:

 
html { font-size:100%; }
td,input,select,textarea,button { font-size:1em; }
 

Where can i use the em unit?

The em unit is most commonly used on font-size, but it isn't limited to that use.

If you have set font-size in em unit, and you need to set a line-height, remember to set it in em and not pixel. Its a common mistake to make. When users set browser text size higher, the text grows, but line height stays the same. This makes the text overlap.

Its also possible to set image height and width using em. Just use the formula in the "Calculating pixel to em" section. Example, if an image is 120 pixel width, its would be 0,0625 x 120 = 7,5em.
Using this method will make the images grow as the text grow.
You can even set all your widths and heights to em units, and the entire design will be dynamic width the text.

Tags: , ,

Leave a Reply