0

Hi i'm facing the problem of converting unit into rem dynamically in css

  1. i will set root font-size as 23px
  2. my current font-size is 16px
  3. my expected result should be 16 / 23 => 0.695rem

Question: i want to do this calculation in css 16 / 23 => 0.695rem which is not working

here is how i tried css:

   #im_p{
      font-size: calc(var(--im-p-font / 16)) rem;
    }

here is what i have tried:

const root = document.documentElement;

root.style.setProperty('--im-p-font',23);
#im_p{
  font-size: calc(var(--im-p-font / 16)) rem;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p id="im_p">I'm Paragraph<p>
</body>
</html>

Note: above code css is not working

EaBengaluru
  • 131
  • 2
  • 17
  • 59

1 Answers1

2

The problem is the format for a CSS calc.

Be careful of how you match brackets (the var needs matching brackets) and put the rem in as a multiplier within the calc:

  font-size: calc((var(--im-p-font) / 16) * 1rem);

const root = document.documentElement;

root.style.setProperty('--im-p-font', 23);
#im_p {
  font-size: calc((var(--im-p-font) / 16) * 1rem);
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <p id="im_p">I'm Paragraph
    <p>
</body>

</html>
A Haworth
  • 30,908
  • 4
  • 11
  • 14
  • Great it works !! one question i had let say i have one or both sizes in `px` like so `--im-p-font:23px` or `calc((var(--im-p-font) / 16px) * 1rem);` and i want result in `rem` what is the hack for this case it is not working actually. – EaBengaluru Oct 01 '22 at 05:15
  • You can't do that in CSS calculations. You can't divide by other than a plain number (even if both the top and bottom are in the same units). You'd have to use some JavaScript to get rid of the px. – A Haworth Oct 01 '22 at 06:19