Home > Mobile >  Convert all occurrences of px to rem for responsive design
Convert all occurrences of px to rem for responsive design

Time:06-13

I am a noob web developer and made a big mistake. I am creating a website for a college project, it needs to be responsive. I have tons of CSS written all in px units. But now for responsiveness, I want to convert all the px to rem. It would be a tiring task to do it one by one. Is there any tool that can help me?

CodePudding user response:

I don't know of any tool that would automatically change all px to rems but you can make the changes quickly if you do something like this:

body {
   font-size: 0.625rem; 
{

Now 1 rem will be equal to 10 px, if you use Vscode you can enter a shortcut Ctrl F and choose a Use Regular Expression option in Find input. Then you can type (\d*)?(\d).?(\d*)?px in Find field, and $1.$2$3rem in Replace field. But be alert, this regex doesn't work for sizes beginning with dot like .5px.

The search bar should look like this: enter image description here

If you want to learn how this regular expression works click here.

CodePudding user response:

Regex shouldn't be used this way, but...

This function should work but the predicament you are in is usually a one time thing and I normally advise against using Regex in this manner. The function pxToRem():

  • Finds all occurrences of a number (even with a decimal) adjacent to the letters 'px'.
  • Then a replacer function takes the number part and divides it by 16
  • Next it suffixes the new number with 'rem' and replaces the old number and 'px'.

Usage

  • Open your stylesheet, select as much of the text you need to change and copy it.
  • Next, paste it on a blank .html or .js file.
  • Wrap the text in grave marks ``` on a QWERTY keyboard it's the key located upper left hand corner `~
  • Assign the string to a variable.
  • Copy and paste pxToRem() code to the same page.

let css = `.box {width: 32px; height: 16px; border: 6px; padding 2.5px;}`;

function pxToRem(CSSString) {
  const rgx = new RegExp(/(\d \.?\d*)px/, 'g');
  return CSSString.replace(rgx, (match, n) => (n / 16)   'rem');
}

console.log(pxToRem(css));

Keep in mind that rem are relative to the font-size set on :root/html and if that font-size happens to be absolute (like the default of 16px) then the styles with rem aren't responsive, but they have the potential to be responsive. If you use a vmin units all rem will react immediately to any changes to the viewport. This not for the faint of heart.

  • Related