Created
April 28, 2011 16:33
-
-
Save scottjehl/946707 to your computer and use it in GitHub Desktop.
emToPx - convert global em-based values to pixels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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 )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
to
otherwise... 👍