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() 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.
Try out the interactive example to view it in action and see how em values cascade in CSS.
The following code shows how to obtain the em value of the
When no element is passed,
getEmPixels returns the rem value of the
You can then use these values to calculate the width of an element in ems or rems.
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).
- Learn about font-size bugs in WebKit an Opera