从SCSS变量创建CSS自定义属性 [英] Create CSS custom properties from SCSS variables

查看:1042
本文介绍了从SCSS变量创建CSS自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个颜色名称和值的SCSS映射。我想像这样创建CSS自定义属性:

I have an SCSS map of colour names and values. I want to create CSS custom properties from them like so:

SCSS

$colours:(
  "gray-500":    #f7fafc,
  "red-500":     #f56565,
  "green-500":   #48bb78
);

所需的结果CSS

--gray-500:  #f7fafc;
--red-500:   #f56565;
--green-500: #48bb78;

我知道如何遍历地图,但是我被赶上的地方是如何使用键作为自定义属性名称,以及如何在其前添加-。我能找到的所有与此主题相关的示例都涉及手动键入自定义属性名称-而不是从地图的键中收集它。

I know how to loop through the map, but where I'm getting caught up is how to use the key as a custom property name, and how to prepend -- to it. All the examples I can find related to this topic involve manually typing out the custom property name - not gleaning it from the key of a map.

这就是我所拥有的远:

@each $colour, $value in $colours {
    --#{$colour}:$value;
}

这会产生错误:预期为 { ,插入符号指向此行的结尾:

That generates an error: expected "{" with the caret pointing to the end of this line:

--#{$colour}:$value;

我正在使用Dart Sass 1.23.7

I'm using Dart Sass 1.23.7

推荐答案

将SCSS转换为CSS 即可以下内容:

:root {
  $colours:(
    "gray-500": #f7fafc,
    "red-500": #f56565,
    "green-500": #48bb78
  );

  @each $key_name, $value in $colours {
    --#{$key_name}: #{$value};
  }
}

在jsfiddle.net上演示

SASS转换为CSS ,您必须在<$ c $中使用 @each c>:root 元素(或在内部定义元素):

On SASS to CSS you have to use the @each inside a :root element (or defining an element inside):

$colours:(
  "gray-500": #f7fafc,
  "red-500": #f56565,
  "green-500": #48bb78
);

:root {
  @each $key, $value in $colours {
    --#{$key}: #{$value};
  }
}

这篇关于从SCSS变量创建CSS自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆