Skip to content

Instantly share code, notes, and snippets.

@miladd3
Last active June 27, 2024 11:36
Show Gist options
  • Save miladd3/17ed397bddd3d0333035c5a5d6c35a8a to your computer and use it in GitHub Desktop.
Save miladd3/17ed397bddd3d0333035c5a5d6c35a8a to your computer and use it in GitHub Desktop.
Javascript px to Rem function
/**
* Converts pixel size to rem and accepts the base as second argument. default base is 16px
*
* @param {number|string} px
* @param {number} base
* @return {string}
*/
const remCalc = (px: number | string, base: number = 16) => {
const tempPx = `${px}`.replace('px', '')
return (1 / base) * parseInt(tempPx) + 'rem'
}
@miladd3
Copy link
Author

miladd3 commented May 21, 2024

Simplified this a bit and made TS happy:

const remCalc = (px: number | string, base: number = 16) => {
  const tempPx = `${px}`.replace('px', '')

  return (1 / base) * parseInt(tempPx) + 'rem'
}

Great, sweet and simple, updated the code to this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment