Em values in JavaScript

If you don’t know what ems are or why you would use them, now is the time. Em units are extremely useful and are an essential component of responsive Web design (RWD). Unfortunately, browsers have failed to provide support for ems in JavaScript.

I needed to reliably convert the pixel width value of an element to ems. Blindly dividing by a hard-coded value of 16 wasn’t an option. Doing so would have resulted in errors when elements had varying font sizes or when a user changed the base font size.

GetEmPixels

getEmPixels() allows you to accurately obtain an element's em value in pixels. This makes dealing with the cascading inheritance of ems simple. It can also be used to find the root em (rem) value of a page.

Interactive Example

Try out the interactive example to view it in action and see how em values cascade in CSS.

getEmPixel example

Basic Examples

The following code shows how to obtain the em value of the #footer element.

var footer = document.getElementById('footer');
var footerEm = getEmPixels(footer);

When no element is passed, getEmPixels returns the rem value of the documentElement.

var rem = getEmPixels();

You can then use these values to calculate the width of an element in ems or rems.

var footerEmWidth = footer.clientWidth / footerEm;
var footerRemWidth = footer.clientWidth / rem;
View full example on CodePen

Size and delivery

GetEmPixels weighs in at a mere 481 bytes (0.47 KB). Feel free to contribute or fork the code on GitHub (once it receives ~100 stars it will be placed on CDNJS).

Get the Script

Related

No Responses

Leave a comment or contact me on Twitter @TysonMatanich

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>