简体   繁体   English

循环 SCSS 变量以生成 CSS 变量

[英]Loop over a SCSS variable to generate CSS variables

I would like if it's possible get css variables from sass variable.我想是否有可能从 sass 变量中获取 css 变量。 I have the next sass variable:我有下一个 sass 变量:

$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:预期的 output 结果:

--breakpoint-xs: 0;
--breakpoint-sm: 576px;
--breakpoint-md: 768px;
--breakpoint-lg: 992px;
--breakpoint-xl: 1200px;
--breakpoint-xxl: 1400px;

Change your loop as below.如下更改您的循环。 Notice I replaced $val by #{$val} :请注意,我将$val替换为#{$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).语法#{…}称为插值,它是将动态值注入 CSS 变量(自定义属性)的唯一方法。 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. CSS 自定义属性,也称为 CSS 变量,具有不寻常的声明语法:它们允许在其声明值中包含几乎任何文本。 What's more, those values are accessible to JavaScript, so any value might potentially be relevant to the user.此外,JavaScript 可以访问这些值,因此任何值都可能与用户相关。 This includes values that would normally be parsed as SassScript.这包括通常会被解析为 SassScript 的值。

Because of this, Sass parses custom property declarations differently than other property declarations.因此,Sass 解析自定义属性声明的方式与其他属性声明不同。 All tokens, including those that look like SassScript, are passed through to CSS as-is.所有令牌,包括那些看起来像 SassScript 的令牌,都按原样传递给 CSS。 The only exception is interpolation , which is the only way to inject dynamic values into a custom property.唯一的例外是interpolation ,这是将动态值注入自定义属性的唯一方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM