With a variety of browsers flooding the market and fluid design being a concern, Front-End developers try to be more alert with their code and the unit of measurements they use in their codes. When it comes to the font size, developers usually demand the unit of measurement of font sizes to be converted from Px to EM or Percentage. I’ve seen people struggling with the conversion of PX unit to EM. So I thought lets help out these developer friends of mine spread over the world with the PX to EM conversion calculation.

So, how is the EM value calculated ?

The calculation of PX to EM is quite easy to understand. One important point to remember is that by default most of the browsers assume the font-size to be 16px. Now it means that by default a font-size of 100% or 1em (100% = 1em) would be equal to 16px.

I.e.

So now we know that 1em = 16px. Now let’s say I need to convert a font-size of 12px to em, how do I calculate it?

The formula for px to em conversion is:

Px value to be converted / Current base Px value*

*Current base Px = Parent element’s font-Size

For example:

If I need to convert 12px to its equivalent Em, I need to divide it by the base px value which is 16px in our case. So it would be (12/16) em, which gives us 0.75em.

The base px would be the parent element’s font-size.  Let’s take the following code as example:

In the above code we see that the body element’s font-size is 14px. So what would be its equivalent Em size?

Remember that by default all the browsers consider the font-size to be 16px. So,

14px = (14/16) em

14px = 0.875em.

Now, what would be the Em equivalent of 12px?

It would be,

12px = (12/14) em

12px = 0.857em

I know you would be thinking how can I take 14px as the base.  But let’s look at the formula once again.

The formula for px to em conversion is:

Px value to be converted / Current base Px value*

*Current base Px = Parent element’s font-Size

Here the parent element for the div “mainDiv” is the body, and the font-size of body element is 14px. Hence while calculating the Em equivalent for the div “mainDiv” we take 14px as the base.

Similarly, while calculating the Em equivalent for the paragraph under the div “mainDiv”, we take 12px as the base for the parent element of the paragraph is the div “mainDiv” and “mainDiv” has font-size as 12px. So the Em equivalent of the paragraph under “mainDiv” would be 10/12Em, i.e. 0.8333em. So here it the updated css for the code above, with the font values converted from px to em,

 

Some px to em or percentage conversion tools

There are many online px to em calculators and charts also available like

http://pxtoem.com/

 

Now you know that Px to Em conversion is an easy task. You just have to remember the parent element’s font-size value. You can also use tools such as firebug to find out what is the computed font-size of the parent element.

Happy coding :) !