public
Last active

emToPx - convert global em-based values to pixels

  • Download Gist
emToPx.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
/*
* emToPx: convert a global em-based value to pixels
* Copyright 2011, Scott Jehl, scottjehl.com
* MIT License
* Usage: emToPx function accepts a single number/float argument, returns a number
*/
var emToPx = (function( win ){
var doc = win.document,
body = doc.body,
prop = "fontSize",
dSize = 16,
valCache = {},
fBody;
return function( val ){
if( !valCache[ val ] ){
//no body yet?
if( !body ){
fBody = doc.createElement( "body" );
var docElem = doc.documentElement;
docElem.insertBefore( fBody, docElem.firstElementChild || docElem.firstChild );
body = fBody;
}
//get body's font size
if( body.currentStyle ){
dSize = body.currentStyle.fontSize;
}
else if( window.getComputedStyle ){
window.getComputedStyle( body,null ).getPropertyValue( "height" );
}
//cache val for repeat lookups
valCache[ val ] = Math.round( val * dSize );
}
return valCache[ val ];
};
}( this ));
window.getComputedStyle( body,null ).getPropertyValue( "height" )

to

getComputedStyle( body,null ).height

otherwise... :+1:

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.