Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can not use sass variables to define value of css variable

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
like image 580
Krzysztof Kaczyński Avatar asked Oct 19 '25 14:10

Krzysztof Kaczyński


1 Answers

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};
}
like image 171
Temani Afif Avatar answered Oct 21 '25 07:10

Temani Afif