有没有办法直接在 class 属性中使用 bootstrap 5 自定义颜色?

is there a way to use bootstrap 5 custom color directly in the class attribute?

就像我们一样:

<span class="text-primary">some text</span>

想知道有没有办法:

<span class="text-red-300">some text</span>

red-300 是 bootstrap 5 种自定义颜色,以下 link 中还有其他颜色。 https://getbootstrap.com/docs/5.0/customize/color/

没办法直接在CSS中使用$red-300。只能使用 SASS 因为 $red-300 是一个 SASS 变量。

但是,基色也可用作 CSS variables。例如,--bs-red$red$red-500 相同。所以,它可以像这样用作 CSS 变量...

.text-red-500 {
   color: var(--bs-red);
}

CSS Demo

如果你想对$red-300使用SASS,可以这样做:

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

.text-red-300 {
    color: $red-300;
}

SASS demo

确实没有 Bootstrap 本机 类 或混入来实现开箱即用。另一方面... Bootsstrap 是为扩展而构建的:使用 SASS 你可以扩展 Bootstrap 并即时创建助手 类 .

注意: 下面的 SASS 代码示例是针对您的问题完成的(= 所有颜色 = 900 个额外的助手 类)。也许您可能希望通过仅将颜色 类 构建为您确实需要的颜色来减少大量的附加代码。请随时根据您的需要调整该代码。


//### make sure you have imported bootstrap function & variables first
@import 'functions';
@import 'variables';



//### SASS function to extend Bootstrap
//### --> quick and dirty demo example!!!

@mixin make-color-classes( $class_prefix, $color_name, $color ){

    // note: positive values = tint | negative values = shade
    $swatch_variations: (80%, 60%, 40%, 20%, 0, -20%, -40%, -60%, -80%);

    $i: 1;
    @each $variation in $swatch_variations {

        // process bootstrap color
        @if ($variation > 0){
            $swatch_color: tint($color);
        }@else if ($variation < 0) {
            $variation: $variation * -1;
            $swatch_color: shade($color);
        }@else{
            $swatch_color: $color;
        }

        // write class
        $color_number: $i * 100;
        .#{$class_prefix}-#{$color_name}-#{$color_number} {
            color: tint-color($color, $variation );
        }

        $i: $i + 1;
    } 

}




//### NOW: 
//### create helper classes for a single color

@include make-color-classes('text', 'blue', $blue);



//### NOW EXTENDED:
//### create helper classes for all named default bootstrap colors

$colors_to_use: $colors;
@each $color_name, $color in $colors_to_use {
        @include make-color-classes('text', $color_name, $color);
}