gpt4 book ai didi

css - 设置 SASS 变量取决于

转载 作者:行者123 更新时间:2023-11-28 16:02:31 24 4
gpt4 key购买 nike

我正在寻找一种根据 body 标签上的类别使用特定颜色的方法。

我有一个像这样的主 scss 文件

// variables.scss
$bg-main: white;
$color-first: red;
$color-second: green;

在我的其他文件中,我使用颜色

// content.scss
.content {
.some-selector: {
// some styles
color: $color-second;
}
a:hover {
// some styles
color: $color-second;
}
}

// and same goes for menu.scss etc.

现在我在主体上有一个动态类,它会根据当前选择的菜单而变化。我希望每个 body 类别的 $color-second 都不同,但我不知道该怎么做。我找到的唯一解决方案是将每个文件中的所有 $color-second 移动到一个文件中,如下所示:

.body-1 {
.content a:hover, .content .some-selector {
color: green;
}
}
.body-2 {
.content a:hover, .content .some-selector {
color: blue;
}
}
.body-1 {
.content a:hover, .content .some-selector {
color: black;
}
}

所以我不需要在每个文件中写颜色。这很好用,但如果我需要将此 $color-second 设置为其他选择器,我需要将其放入这个大文件中。

这有可能以其他方式做到这一点吗?

我已经检查了这些答案,但对我帮助不大:

最佳答案

有多种方法可以做到这一点。想到的最明显的两个是混合和循环:

混合

只需将您想要的所有内容放入一个 mixin 中,然后将其用于每个主体类:

@mixin colored-content($color) {
.content a:hover, .content .some-selector {
color: $color;
}

/* Any other rules which use $color here */
}

.body-1 {
@include colored-content(green);
}

.body-2 {
@include colored-content('#FF0000');
}

.body-3 {
@include colored-content(darken(red, 20));
}

您可以使用任意数量的参数(例如,$textColor$bgColor)、条件或规则来扩展此示例。

使用这种方法,您将不会有 SCSS 代码重复,并且可以轻松引入任何更新。

循环

另一种方法是使用简单的循环:

$body_themes: (
"body-1": green,
"body-2": #FF0000,
"body-3": darken(red, 2)
);

@each $body_class, $color in $body_themes {
.#{$body_class} {
.content a:hover, .content .some-selector {
color: $color;
}

/* Any other rules which use $color here */
}
}

它甚至更短,但恕我直言,它的可读性较差。

附言顺便说一下,可以组合 mixin 和循环 :)

关于css - 设置 SASS 变量取决于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39826913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com