[英]Generate CSS classes dynamically based on variables - SCSS
I have color variables (example):我有颜色变量(示例):
// _colors.scss
:root, * {
--color-primary-50: 1,1,1;
--color-primary-100: 2,2,2;
--color-primary-200: 3,3,3;
}
And I want to generate classes based on the variables, for example:我想根据变量生成类,例如:
// _background.scss
.bg-primary-50 {
background: rgb(var(--color-primary-50));
}
.bg-primary-100 {
background: rgb(var(--color-primary-100));
}
.bg-primary-200 {
background: rgb(var(--color-primary-200));
}
I want to simplify my future modifications if I need to change or add new colors and dynamically populate my _background
file with classes based on _colors
variables.如果我需要更改或添加新的 colors 并使用基于_colors
变量的类动态填充我的_background
文件,我想简化我未来的修改。
It seems like a lot of monotonic work.这似乎是很多单调的工作。 Is there any way to get this result?有什么办法可以得到这个结果吗? Perhaps I should change my file structure?也许我应该改变我的文件结构?
use @each
loop.使用@each
循环。 Instead of creating the vars
in :root
add those in a single var
(see below example)不要在:root
中创建vars
,而是将它们添加到单个var
中(参见下面的示例)
$colors : (
"primary-50": "1,1,1",
"primary-100": "2,2,2",
"primary-200": "3,3,3",
);
@each $color, $value in $colors {
.bg-#{$color} {
background-color: rgb($value);
}
}
the above code compiled into上面的代码编译成
.bg-primary-50 {
background-color: #010101;
}
.bg-primary-100 {
background-color: #020202;
}
.bg-primary-200 {
background-color: #030303;
}
And for CSS --variables
对于 CSS --variables
:root {
@each $color, $value in $colors {
--color-#{$color}: rgb($value);
}
}
and you have CSS Variables你有 CSS 个变量
:root {
--color-primary-50: #010101;
--color-primary-100: #020202;
--color-primary-200: #030303;
}
Like you mentioned in your comment "will this solution work for the light and dark modes?"就像您在评论中提到的“此解决方案是否适用于明暗模式?” for that you can do something like this为此你可以做这样的事情
html[data-color-mode="dark"] {
$dark-mode-colors: (
"primary-color-50": "0, 0, 0",
"primary-color-100": "1, 1, 1",
"primary-color-200": "2, 2, 2",
)
@each $color, $value in $colors {
.bg-#{$color} {
background-color: $value;
}
}
}
// change your color scheme as you prefer method will remain the same
html[data-color-mode="light"] {
$light-mode-colors: (
"primary-color-50": "0, 0, 0",
"primary-color-100": "1, 1, 1",
"primary-color-200": "2, 2, 2",
)
@each $color, $value in $colors {
.bg-#{$color} {
background-color: $value;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.