Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like we do:

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

I want to know if there is a way to do:

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

red-300 is a bootstrap 5 custom color and there are others in the following link. https://getbootstrap.com/docs/5.0/customize/color/

like image 288
Gnopor Avatar asked Mar 28 '21 19:03

Gnopor


2 Answers

There is no way to use $red-300 directly in CSS. It's only possible using SASS because $red-300 is a SASS variable.

However, the base colors are also available as CSS variables. For example, --bs-red is the same as $red and $red-500. So, it could be used as a CSS variable like this...

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

CSS Demo

If you wanted to use SASS for $red-300, it would be done like this:

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

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

SASS demo

like image 85
Zim Avatar answered Nov 09 '22 01:11

Zim


Indeed there are no Bootstrap native classes or mixins to realise that out of the box. On the other hand ... Bootsstrap is build to be extended: Using SASS you can extend Bootstrap and create the helper classes on the fly.

NOTE: The SASS code example below is done to YOUR QUESTION (= all colors = 900 additional helper classes). Maybe you may like to reduce that huge amount of additional code by building the color classes only to your indeed needed colors. Please feel free to adapt that code to your needs.


//### 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);
}




like image 36
Brebber Avatar answered Nov 09 '22 01:11

Brebber