根据变量动态生成 CSS 类 - SCSS

Ant*_*yev 3 css sass scss-mixins

我有颜色变量(示例):


// _colors.scss
:root, * {
  --color-primary-50: 1,1,1;
  --color-primary-100: 2,2,2;
  --color-primary-200: 3,3,3;
}
Run Code Online (Sandbox Code Playgroud)

我想根据变量生成类,例如:


// _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));
}

Run Code Online (Sandbox Code Playgroud)

如果我需要更改或添加新颜色并_background使用基于_colors变量的类动态填充我的文件,我想简化未来的修改。

这似乎是很多单调的工作。有什么办法可以得到这个结果吗?也许我应该改变我的文件结构?

Kun*_*war 8

使用@each循环。不要在单个中创建添加这些vars(请参见下面的示例):rootvar

$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);
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码编译成

$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);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于 CSS--variables

:root {
    @each $color, $value in $colors {
        --color-#{$color}: rgb($value);
    }
}
Run Code Online (Sandbox Code Playgroud)

并且你有 CSS 变量

.bg-primary-50 {
  background-color: #010101;
}
.bg-primary-100 {
  background-color: #020202;
}
.bg-primary-200 {
  background-color: #030303;
}
Run Code Online (Sandbox Code Playgroud)

就像您在评论中提到的“这个解决方案适用于浅色和深色模式吗?” 为此你可以做这样的事情

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;
    }
  }
}

Run Code Online (Sandbox Code Playgroud)