Skip to content

Instantly share code, notes, and snippets.

@stilist
Created May 19, 2010 06:10
Show Gist options
  • Save stilist/406015 to your computer and use it in GitHub Desktop.
Save stilist/406015 to your computer and use it in GitHub Desktop.
// Sometimes you want to know the exact pixel dimension of a CSS property, but it’s
// in non-pixel units. This hack might help you out.
//
// Note: assumes a jQuery object `$`.
//
// License: http://github.com/stilist/ratafiacurrant/blob/master/License
var cssDimensionInPx = (function () {
return function ($element, property) {
var dimension = $element.css(property);
var dimensionInt = parseInt(dimension, 10);
var fontSize = parseInt($element.css("font-size"), 10);
if (dimension && !isNaN(dimensionInt)) {
// no unit
if ("" + dimensionInt === dimension) {
return dimensionInt;
// px
} else if (dimension.length - 2 === dimension.indexOf("px")) {
return dimensionInt;
// em
} else if (dimension.length - 2 === dimension.indexOf("em")) {
return dimensionInt * fontSize;
// %
} else if (dimension.length - 1 === dimension.indexOf("%")) {
return (dimensionInt * 0.01) * fontSize;
}
} else {
return 0;
}
};
})();
alert(cssDimensionInPx($("body"), "width"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment