【问题标题】:is there a way to use bootstrap 5 custom color directly in the class attribute?有没有办法直接在类属性中使用 bootstrap 5 自定义颜色?
【发布时间】:2021-06-24 23:03:30
【问题描述】:

像我们一样:

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

我想知道有没有办法:

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

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

【问题讨论】:

    标签: css sass css-variables bootstrap-5


    【解决方案1】:

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

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

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

    CSS Demo

    如果您想将 SASS 用于$red-300,可以这样完成:

    @import "functions";
    @import "variables";
    
    .text-red-300 {
        color: $red-300;
    }
    

    SASS demo

    【讨论】:

      【解决方案2】:

      确实没有 Bootstrap 原生类或 mixin 来实现开箱即用。另一方面...... 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);
      }
      
      
      
      
      

      【讨论】:

        猜你喜欢
        • 2021-08-29
        • 1970-01-01
        • 2021-12-24
        • 2016-08-25
        • 2021-04-23
        • 2023-01-26
        • 2018-09-16
        • 2019-04-26
        相关资源
        最近更新 更多