Converting Em To Px In Javascript (and Getting Default Font Size)


Answer :

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.



I have a better answer. My code will store the length of 1em (in CSS pixel px units in the JavaScript variable em:




  1. 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>

  2. 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.



If you need something quick and dirty (and based on base font-size of body, not an element), I'd go with:



Number(getComputedStyle(document.body,null).fontSize.replace(/[^\d]/g, ''))

Number( // Casts numeric strings to number
getComputedStyle( // takes element and returns CSSStyleDeclaration object
document.body,null) // use document.body to get first "styled" element
.fontSize // get fontSize property
.replace(/[^\d]/g, '') // simple regex that will strip out non-numbers
) // returns number


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable