2

I am building a multi site application built on one framework, using Bootstrap 4 with Webpack.

I want to dynamically change some variables of Bootstrap depending on the base class on the body element. i.e:

.class1{
    $theme-colours: (
        primary: red,
    );
 }

.class2{
    $theme-colours: (
        primary: blue,
    );
 }

Then:

<body class="class1">
    <h1 class="text-primary">RED TEXT</h1> 
</body>

And:

<body class="class2">
    <h1 class="text-primary">BLUE TEXT</h1> 
</body>

Is this possible in SASS? I have tried using mixin but getting no success...

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
Joe Saunderson
  • 143
  • 1
  • 8

1 Answers1

2

You'd have to "rebuild" the -primary classes using the various Bootstrap 4 theme color functions/mixins. The primary color changes could go into a custom @mixin, making it easier to build each primary "theme":

@mixin build-primary-classes($color) {
    @include bg-variant(".bg-primary", $color);
    
    .btn-primary {
        @include button-variant($color, $color);
    }
  
    .btn-outline-primary {
        @include button-outline-variant($color);
    }
    
    @include text-emphasis-variant(".text-primary", $color);
    
    .border-primary {
        border-color: $color !important;
    }
}


.theme1 {
    @include build-primary-classes($purple);
}

.theme2 {
    @include build-primary-classes($red);
}

https://codeply.com/go/c3KTMWlDCb

Taking it a step further, you could put the "$customthemes" in a map, and then generate the theme classes.

$customthemes: (
  "theme1": purple,
  "theme2": cyan,
  "theme3": orange
);

@each $themeName, $color in $customthemes {
  .#{$themeName} {
    @include build-primary-classes($color);
  }
}

https://codeply.com/go/81ukKyAZbS


Then, if you're using Webpack, pass in the $customthemes map to the extract-text-webpack-plugin and SASS-loader. Pass in the $customthemes using the data option...

webpack-config:

     ....
     use: extractSass.extract({
         use: [

                  {
                    loader: "sass-loader",
                    options: {
                      allChunks: true,
                      data: '$customthemes:("theme1":purple,"theme2":pink,"theme3":red);'
                    }
                }]
         })
      .....

Just remember that if you have too many $customthemes the CSS is going to get really large. I prefer generating separate theme.css files with SASS and then refer to any theme.css as needed in the HTML HEAD.

Related:
How to extend/modify (customize) Bootstrap 4 with SASS
How to change the bootstrap primary color?

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