Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Created July 12, 2023 15:10
Show Gist options
  • Save smitroshin/bd408738d567f7be98dd12aa360a9f50 to your computer and use it in GitHub Desktop.
Save smitroshin/bd408738d567f7be98dd12aa360a9f50 to your computer and use it in GitHub Desktop.
Convert "px" to "rem"
/**
* 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