I would like if it's possible get css variables from sass variable. I have the next sass variable:
$grid-breakpoints: (
xs: 0,
sm: 576px,
md: 768px,
lg: 992px,
xl: 1200px,
xxl: 1400px,
);
And I'm trying to do an iteration as the next:
@each $key,$val in $breakpoints{
// Here I want to generate the css variables with a for or manually
--breakpoint-#{$key}: $val; // I tried to do something like this but it doesn't works
}
Expected output result:
--breakpoint-xs: 0;
--breakpoint-sm: 576px;
--breakpoint-md: 768px;
--breakpoint-lg: 992px;
--breakpoint-xl: 1200px;
--breakpoint-xxl: 1400px;
CodePudding user response:
Change your loop as below. Notice I replaced $val
by #{$val}
:
:root {
@each $key, $val in $grid-breakpoints {
--breakpoint-#{$key}: #{$val};
}
}
The syntax #{…}
is called interpolation and it is the only way to inject dynamic values into a CSS variable (custom property). Here is a quote from the doc:
CSS custom properties, also known as CSS variables, have an unusual declaration syntax: they allow almost any text at all in their declaration values. What’s more, those values are accessible to JavaScript, so any value might potentially be relevant to the user. This includes values that would normally be parsed as SassScript.
Because of this, Sass parses custom property declarations differently than other property declarations. All tokens, including those that look like SassScript, are passed through to CSS as-is. The only exception is
interpolation
, which is the only way to inject dynamic values into a custom property.
$primary: red;
:root {
--primary: #{$primary}; // this one works
--primary: $primary; // this does not
}