Skip to content

Instantly share code, notes, and snippets.

@ryanmorr
Last active March 29, 2024 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanmorr/46afba3bf58c3f9b879b07aaddb040f4 to your computer and use it in GitHub Desktop.
Save ryanmorr/46afba3bf58c3f9b879b07aaddb040f4 to your computer and use it in GitHub Desktop.
A hack to get the value of a CSS style property in the provided unit
// For certain CSS properties (width, height, etc.) getComputedStyle() will return the
// "used value" (https://developer.mozilla.org/en-US/docs/Web/CSS/used_value) in pixels,
// regardless of what units it was explicitly defined with. This function allows you to
// get the value in any unit provided
function getStyleInUnit(el, prop, unit) {
let value = parseFloat(getComputedStyle(el)[prop]) || 0;
if (unit !== 'px') {
el.style[prop] = 1 + unit;
value = (1 / parseFloat(getComputedStyle(el)[prop])) * value;
el.style[prop] = value + unit;
}
return value;
}
// Usage:
const el = document.querySelector('div'); //=> <div style="width: 5em"></div>
getComputedStyle(el).width; //=> "80px"
getStyleInUnit(el, 'width', 'em'); //=> 5
getStyleInUnit(el, 'width', '%'); //=> 4.203159725323512
getStyleInUnit(el, 'width', 'pt'); //=> 60.01267503168758
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment