Created
July 12, 2023 15:10
-
-
Save smitroshin/bd408738d567f7be98dd12aa360a9f50 to your computer and use it in GitHub Desktop.
Convert "px" to "rem"
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
/** | |
* Assuming 1rem = 16px | |
* | |
* 14 => 0.875 | |
*/ | |
export const pxToRem = (val: number, htmlFontSize?: number) => val / (htmlFontSize ?? 16); | |
/** | |
* Assuming 1rem = 16px | |
* | |
* 14 => "0.875rem" | |
*/ | |
export const toRem = (val: number, htmlFontSize?: number) => `${pxToRem(val, htmlFontSize)}rem`; | |
/** | |
* Assuming 1rem = 16px | |
* | |
* "9px 4px 6px 4px" => "0.5625rem 0.25rem 0.375rem 0.25rem" | |
*/ | |
export const replacePxByRem = (str: string, htmlFontSize?: number) => { | |
const regex = /(\d+)px/g; | |
return str.replace(regex, (pxValue) => toRem(parseFloat(pxValue), htmlFontSize)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment