Tuesday, 14 February 2012

What are CSS em sizes?

Introduction
I thought I'd write a short post about CSS em sizes covering what they are and how to use them, I have just thought recently they're not all that easy to understand without reading about it somewhere which is what's caused me to write this post.

What is an em?
It's a flexible unit of size used in CSS mainly for defining the size of a font, what do I mean by flexible?  Well it changes relative to the font size of its parent, kind of like a pixels size is relative to the DPI settings if that helps.

For example if you had a document with a default text size of 16 pixels (the default for most modern browsers) then 1em = 16px, if the default was 10 pixels then 1em = 10px.  This only changes if the parent has a different font size set, for example if a document has a default font size of 16 pixels but you have a container within it with a font size of 12 pixels then 1em = 12px within that container.

Why are they called ems?
It comes from typography as I understand it, em is is pronounced just like it looks and exactly the same as the letter 'm'.  It is used as a measurement of the width for the letter 'M' within the font, this letter is used because it should be the widest in the alphabet, I guess there might be some strange font out there where this isn't the case though.

Why use ems and not just pixels?
The main reason used to be that if the user wanted to increase the text size within their browser they could not do so with pixel defined sizes but could do it with relative defined sizes such as percentages and ems.  This isn't as much of a problem now as modern browsers all zoom the whole page rather than just making the text bigger, one exception to this is Internet Explorer 8 and below which won't zoom text defined in pixel sizes.  There are also all the older versions of browsers from other vendors which pre-date page zooming which won't magnify text defined in pixels, although I believe those ones are dwindling in number quite rapidly (I don't have any facts to back that statement up).

How to use ems properly
Well firstly declare your default pixel size, I'd recommend 16px as it's a good read able size and I'll put a link to an article about it at the end of this post.  Example code below:

html, body{ font-size: 16px; }

Now lets say you wanted to make your heading 1 tags 24 pixels large you take the target size (24) and divide it by the parent size (16) and that will give you the em number you need to use.  I've written this down a bit more mathematically & given an example below:

target size / parent size = em size

24px / 16px = 1.5em

That's all I'm going to say on this subject for now, have a look around on the net for more information if you're interested but I think this is enough to get going with CSS em sizes.

Further reading

No comments:

Post a Comment