Skip to content

Instantly share code, notes, and snippets.

@autr
Last active September 19, 2022 22:59
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 autr/feb0acdfa8a66b122a5cd066396f0746 to your computer and use it in GitHub Desktop.
Save autr/feb0acdfa8a66b122a5cd066396f0746 to your computer and use it in GitHub Desktop.
Calculate pixels from CSS value.
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