CSS 使用另一个 class 的颜色?

CSS use color from another class?

是否可以将颜色从一个 CSS class 导入另一个?或者创建某种全局颜色定义,然后在多个 class 中使用它,这样如果您想更改颜色就不必在多个地方更新?

例如,假设我有一个 CSS class,我想将其用于特定元素,但我希望它使用分配给 Bootstrap [=16= 的相同颜色] class。有什么办法吗?或者我只需要从 Bootstrap CSS 文件中复制颜色值并在我自己的 class 中使用它?

使用 SCSS

分配变量:

$darkGrey: #7a7a7a;

使用这些变量:

ul, .hero, .homepage, .anotherClass {
  background: $darkGrey;
}

更多信息:https://responsivedesign.is/articles/difference-between-sass-and-scss/

您可能还想查看 Bootstrap 4 中的新 CSS variables。它们可以让您覆盖颜色,但您需要重新定义 CSS class.

CSS variables offer similar flexibility to Sass’s variables, but without the need for compilation before being served to the browser.

例如:

.text-teal {
  color: var(--teal);
}

Bootstrap 4 CSS Variables Demo

您可以在 ::root 选择器中指定全局颜色,如下例所示:

:root{
     --green-color:#fff123;
}

并在 css 中使用 var() 函数的任何地方使用此颜色,例如:

.container{
    background-color:var(--green-color);
}

.column{
   color:var(--green-color);
}