0

I am trying to implement a dark/light theme to my project. I have successfully managed to override some core Bootstrap styles to achieve a dark/light mode by using a separate SCSS file that is imported after the main Bootstrap file. What I am trying to figure out is how to allow the user to toggle between these two modes at runtime.

I have tried applying a toggle button that adds the 'dark-mode' class to the body but this seems to leave out all the Bootstrap specific styles:

My custom SCSS:

.dark-mode{
    
    $body-bg: rgb(41, 41, 41);
    $card-bg: rgb(78, 78, 78);

    $primary: rgb(0, 183, 255);
    $secondary: white;
    $danger: rgb(255, 60, 60);
    $success: rgb(1, 197, 1);

    h6, h1, h4, h5, p{
        color: white;
    }

    $dark: white;
    $light: $body-bg;
    $modal-content-bg: $card-bg;

    $carousel-indicator-height: 0px;

}@import '../../node_modules/bootstrap/scss/bootstrap.scss';

Javascript/Vue:

toggleDarkMode(){
    const el = document.body
    el.classList.toggle("dark-mode");
  }

I can see the 'dark-mode' class added to the body when I press the toggle button, and I can see all the headings change (h6, h1 etc.) but all the Bootstrap-specific styles remain the same. I thought it would be as simple as this because if I remove the 'dark-mode' class parentheses from the overrides in the SCSS file and reload the browser the dark mode works. I assume there is a proper way to do this but I am not too familiar with SCSS. Please can someone advise?

Thanks

mellows
  • 303
  • 1
  • 7
  • 27

1 Answers1

1

Similar to this question, you need to @import "bootstrap" within the .dark-mode class definition in order for the Bootstrap variables to be "reset". Also notice you may need to redefine the CSS variables...

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

.dark-mode{
    
    $body-bg: rgb(41, 41, 41);
    $card-bg: rgb(78, 78, 78);

    $primary: rgb(0, 183, 255);
    $secondary: white;
    $danger: rgb(255, 60, 60);
    $success: rgb(1, 197, 1);
    
    $theme-colors: (
        "primary": $primary,
        "secondary": $secondary,
        "success": $success,
        "danger": $danger,
        "info": $indigo,
        "dark": $dark,
        "light": $light,
    );


    h6, h1, h2, h4, h5, p {
        color: white;
    }

    $dark: white;
    $light: $body-bg;
    $modal-content-bg: $card-bg;

    $carousel-indicator-height: 0px;
    
    --#{$variable-prefix}body-color: #{$body-color};
    --#{$variable-prefix}body-bg: #{$body-bg};

    @import "bootstrap";

}

https://codeply.com/p/KVZwIZi8OG

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624