Last active
March 29, 2024 00:29
-
-
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
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
// 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