4

I am trying to use sass variables and sass mathematical operator to define different css font-size variables.

I defined css variables like that:

$base-font-size: 1rem;

:root {
  --font-size-s: #{$base-font-size} * 0.5;
  --font-size-m: #{$base-font-size};
  --font-size-l: #{$base-font-size} * 2;
}

Then in other file I used my css variable like that:

p {
  font-size: var(--font-size-l);
}

This doesn't work at all my font size doesn't change at all. I thought that maybe there is something wrong with sass mathematical operators, so I tried something like that:

p {
  font-size: 1rem * 2;
}

This worked and my font size was equal 2rem as expected. After this discovery I thought that maybe I am doing something wrong with sass variables so changed my css variables to that:

:root {
  --font-size-s: 1rem * 0.5;
  --font-size-m: 1rem;
  --font-size-l: 1rem * 2;
}

And this doesn't work! I really do not know what I am doing wrong. Can someone explain to me how should I define those css variables with sass variables and sass mathematical operators?

Notes:

  • If I use css calc function this will work too:
:root {
  --font-size-s: calc(#{$base-font-size} * 0.5);
  --font-size-m: #{$base-font-size};
  --font-size-l: calc(#{$base-font-size} * 2);
}
  • For compiling .scss files I am using Webpack 5.10.3 with css-loader and sass-loader
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Krzysztof Kaczyński
  • 4,412
  • 6
  • 28
  • 51

1 Answers1

2

You need to evalute all the expression like below:

$base-font-size: 1rem;

:root {
  --font-size-s: #{$base-font-size * 0.5};
  --font-size-m: #{$base-font-size};
  --font-size-l: #{$base-font-size * 2};
}
Temani Afif
  • 245,468
  • 26
  • 309
  • 415