Skip to content

Instantly share code, notes, and snippets.

@whatsnewsisyphus
Created October 31, 2014 11:32
Show Gist options
  • Save whatsnewsisyphus/68adec2fafa72d967fb7 to your computer and use it in GitHub Desktop.
Save whatsnewsisyphus/68adec2fafa72d967fb7 to your computer and use it in GitHub Desktop.
em / rem to px function
/**
* emRemToPx.js | @whatsnewsisyphus
* To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
* see CC0 Public Domain Dedication <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
var emRemToPx = function( value, scope, suffix ) {
if (!scope || value.toLowerCase().indexOf("rem") >= 0) {
scope = 'body';
}
if (suffix === true) {
suffix = 'px';
} else {
suffix = null;
}
var multiplier = parseFloat(value);
var scopeTest = $('<div style="display: none; font-size: 1em; margin: 0; padding:0; height: auto; line-height: 1; border:0;">&nbsp;</div>').appendTo(scope);
var scopeVal = scopeTest.height();
scopeTest.remove();
return Math.round(multiplier * scopeVal) + suffix;
};
@whatsnewsisyphus
Copy link
Author

here is something I cobbled together, scope and suffix are optional. Pass it a rem or em value as string, eg. '4em' [ you can use spaces and upper/lowercase ] and it will return the px value. Unless you give it a scope, which would be the target element for finding the local EM value, it will default to body, effectively giving you the rem value. Lastly, the optional suffix parameter [ boolean ] will add 'px' to the returned value such that 48 becomes 48px for example.

ex: emRemToPx( '3em', '#content' )

return 48 on a font-size 16px / 100% document

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