-1

I have a scss file that I @import "./global-style/scss-variables"; in index.scss, with the following content:

:root {
  --spacing: 8px;
  --iphonewidth: 375px;
}

When I call a variable in the scss of one of my components, like margin-bottom: calc(#{var(--spacing)} * 2);, 8px is inserted in the var(--spacing) placeholder. However, var(--iphonewidth) is not 375px as would've been expected, which is used here:

@media screen and (max-width: var(--iphonewidth)) {
    ....
}

I'm not sure why variables in sass behave this way. Maybe because variables may not be used in media queries?

DSteman
  • 1,388
  • 2
  • 12
  • 25
  • 1
    CSS variables are resolved at runtime, SCSS variables are resolved at compile time, string interpolation in SCSS `#{...}`is resolved at compile time (everything SCSS is compile time). So what does `#{var(--spacing)}` yield? Simple. The string `var(--spacing)` and that is inserted in `calc( __here__ * 2 )` and that will work during runtime. But your second use case is not supported, see this [question and the first answer](https://stackoverflow.com/questions/40722882/css-native-variables-not-working-in-media-queries). – Martin Oct 22 '21 at 20:19
  • Ah okay, that explains. Only after posting this question it came to mind that maybe it has to do with the media query, hence my edit lol. Thanks anyways :) – DSteman Oct 22 '21 at 20:22

1 Answers1

0

For SCSS:

$spacing: 8px;
$iphonewidth: 375px;


.selector {
    margin-bottom: calc( #{$spacing * 2} );
}

For CSS:

:root {
  --spacing: 8px;
  --iphonewidth: 375px;
}

.selector {
  margin-bottom: calc(var(--spacing) * 2);
}