首页 > 解决方案 > Bootstrap 5 - 自定义主题颜色不更新类

问题描述

我刚刚使用 Bootstrap 5 开始了一个新项目,我正在尝试使用一些自定义值设置主题颜色。但是,按照我一直这样做的方式进行操作会给我带来一些问题。

我创建了三种颜色:$primary、$secondary、$tertiary。但是,如果我添加任何类(例如 bg-tertiary),则不会发生任何变化,就好像它不存在一样。bg-primary 仅使用 Bootstrap 定义的默认颜色。

我的代码如下:

@import "bootstrap/_functions";
@import "bootstrap/_variables";

$primary: #ec008c;
$secondary: #1ab7ea;
$tertiary: #3fb247;

$theme-colors: (
    "primary": $primary,
    "secondary": $secondary,
    "tertiary": $tertiary,
    "light": $light,
    "dark": $dark,
);

@import "bootstrap/bootstrap";

如果我将默认值(例如“dark”)更改为使用 $tertiary,则 scss 文件中使用 $dark 的任何代码都会更改为使用 $tertiary 中的值。如下所示:

$theme-colors(
    "dark": $tertiary
);

#pageFooter {
   background: $dark; //This becomes #3fb247 the value from $tertiary
}

我究竟做错了什么?我不明白为什么 scss 文件中的变量会受到 $theme-colors 更改的影响,但类不会。

编辑:

使用 chrome 检查器,我可以看到 .bg-primary 使用 css 变量 --bs-primary-rgb。查看可用变量--bs-primary 已更改为我设置的颜色,但不是--bs-primary-rgb。

我怎样才能改变这个变量。它应该自动完成吗?

随着进一步的研究,这些 rgb 变量似乎已在 Bootstrap 5.1 中引入。我找不到太多关于如何让变量更新为我的设定值的信息,可能是因为它太新了。所以我选择恢复到 5.0.2,现在一切都按我的预期工作。

标签: twitter-bootstrapsassbootstrap-5

解决方案


引导程序 5.1.0

最近对 text- 和 bg- 类创建方式的更改需要在 5.1.0 中进行额外的 SASS 映射合并

@import "functions";
@import "variables";
@import "mixins";

$tertiary: #3fb247;

$theme-colors:map-merge($theme-colors, (
  "tertiary": $tertiary
));

$theme-colors: map-merge($theme-colors, $custom-theme-colors);
$theme-colors-rgb: map-loop($theme-colors, to-rgb, "$value");
$utilities-colors: map-merge($utilities-colors, $theme-colors-rgb);
$utilities-text-colors: map-loop($utilities-colors, rgba-css-var, "$key", "text");
$utilities-bg-colors: map-loop($utilities-colors, rgba-css-var, "$key", "bg");

@import "bootstrap";

引导程序 5.0.2

如果您希望它生成类似,等的类,则需要使用“第三级”变量添加到主题颜色映射中...map-mergebg-tertiarybtn-tertiary

@import "functions";
@import "variables";
@import "mixins";

$tertiary: #3fb247;

$theme-colors:map-merge($theme-colors, (
  "tertiary": $tertiary
));
      
@import "bootstrap";

演示


推荐阅读