Home > Back-end >  How to convert unit into rem dynamically in css
How to convert unit into rem dynamically in css

Time:10-01

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

CodePudding user response:

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>

  • Related