Search code examples
twitter-bootstrapsassbootstrap-5scss-mixins

Create new color scheme for dark-light mode in bootstrap sass


I want to create dark mode for a web site which use bootstrap. I have to add new root class which includes all boostrap colors. Here is my colors.scss:

$primary:#065FC6;
$secondary:#263C5C;
$success:#49C96D;
$danger:#FD7972;
$warning:#FF965D;
$light:#F8F8F8;
$body-color: #263C5C;

$custom-colors: (
  "brd-default": $body-color
  );
  

I want create new class like this:

:root.dark{
    // override colors and classes for dark mode
    $primary:#012345;
    $secondary:#111111;
    $success:#222222;
}

So how can i copy and paste all bootstrap colors for new color scheme?

If i can add colors, i will change HTML class so my root(color scheme) will be:

enter image description here

in my styles.scss:

@import "./colors";// custom colors
@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/utilities";

Solution

  • As explained here, there's no way to attach a class to :root. However, you don't need this to achieve what you want.

    Simply make a dark class then you can add that as desired to the html or body tag.

    Make all the needed theme color changes inside .dark{}, and then @import "bootstrap". When .dark doesn't exist on the body, the theme colors will return to Bootstrap defaults.

    @import "functions";
    @import "variables";
    @import "mixins";
    
    
    .dark {
    
        /* redefine theme colors for dark theme */
        $primary: #012345;
        $secondary: #111111;
        $success: #222222;
        $dark: #000;
        
        $theme-colors: (
            "primary": $primary,
            "secondary": $secondary,
            "success": $success,
            "danger": $danger,
            "info": $indigo,
            "dark": $dark,
            "light": $light,
        );
    
        /* redefine theme color variables */
        @each $color, $value in $theme-colors {
            --#{$variable-prefix}#{$color}: #{$value};
        }
    
        /* redefine theme color rgb vars (used for bg- colors) */
        $theme-colors-rgb: map-loop($theme-colors, to-rgb, "$value");
        @each $color, $value in $theme-colors-rgb {
            --#{$variable-prefix}#{$color}-rgb: #{$value};
        }
    
        $body-color: #eeeeee;
        $body-bg: #263C5C;
        
        --#{$variable-prefix}body-color: #{$body-color};
        --#{$variable-prefix}body-bg: #{$body-bg};
          
        @import "bootstrap";
    }
    
    

    Bootstrap 5 Dark Theme