Last active
September 19, 2022 22:59
-
-
Save autr/feb0acdfa8a66b122a5cd066396f0746 to your computer and use it in GitHub Desktop.
Calculate pixels from CSS value.
This file contains hidden or 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
export function CalculatePixels( str, el ) { | |
try { | |
const value = parseFloat( str ) | |
const unit = str.replace(value, '').toLowerCase() | |
const { innerWidth, innerHeight } = window | |
const run = { | |
['%']: () => (el.offsetWidth * (value/100)), | |
px: () => value, | |
vw: () => (innerWidth * (value/100)), | |
vh: () => (innerHeight * (value/100)), | |
vmax: () => (Math.max(innerWidth,innerHeight) * (value/100)), | |
vmin: () => (Math.min(innerWidth,innerHeight) * (value/100)), | |
em: () => (parseFloat(getComputedStyle(el?.parentElement || document.body).fontSize) * value), | |
rem: () => (parseFloat(getComputedStyle(document.body).fontSize) * value) | |
} | |
return run[unit]() | |
} catch(err) { | |
console.error(`[CalculatePixels] could not parse ${str}:`, err.message) | |
return 0 | |
} | |
} | |
export function MakeTest( divEl ) { | |
const test = ['123px', '50vw', '50vh', '2em', '2rem', '50vmax', '50vmin', '100%' ] | |
const { innerWidth, innerHeight } = window | |
const { offsetWidth, offsetHeight } = divEl || {} | |
for( const t of test ) console.log('testing:', t, CalculatePixels( t, divEl )) | |
console.log({innerHeight, innerWidth, offsetWidth, offsetHeight}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment