Skip to content

Instantly share code, notes, and snippets.

@scottjehl
Created April 28, 2011 16:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottjehl/946707 to your computer and use it in GitHub Desktop.
Save scottjehl/946707 to your computer and use it in GitHub Desktop.
emToPx - convert global em-based values to pixels
/*
* 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 ));
@paulirish
Copy link

window.getComputedStyle( body,null ).getPropertyValue( "height" )

to

getComputedStyle( body,null ).height

otherwise... 👍

@beep
Copy link

beep commented Apr 28, 2011

Awesome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment