Converting em to px in Javascript (and getting default font size)
Solution 1:
Edit: No, there isn't.
To get the rendered font size of a given element, without affecting the DOM:
parseFloat(getComputedStyle(parentElement).fontSize);
This is based off the answer to this question.
Edit:
In IE, you would have to use parentElement.currentStyle["fontSize"]
, but this is not guaranteed to convert the size to px
. So that's out.
Furthermore, this snippet won't get you the default font size of the element, but rather its actual font size, which is important if it has actually got a class and a style associated with it. In other words, if the element's font size is 2em
, you'll get the number of pixels in 2 ems. Unless the font size is specified inline, you won't be able to get the conversion ratio right.
Solution 2:
I have a better answer. My code will store the length of 1em
(in CSS pixel px
units in the JavaScript variable em
:
-
Place this
div
anywhere in your HTML code<div id="div" style="height:0;width:0;outline:none;border:none;padding:none;margin:none;box-sizing:content-box;"></div>
-
Place this function in your JavaScript file
var em; function getValue(id){ var div = document.getElementById(id); div.style.height = '1em'; return ( em = div.offsetHeight ); }
Now, whenever you will call this function 'getValue'
with id of that test div in parameter, you will have a variable name em
which will contain value of 1 em in px.