To create custom themes in Bootstrap 4, you can redefine the -primary
classes using the color functions and mixins provided by Bootstrap. By putting the primary color changes into a custom @mixin
, you can easily 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);
}
Check out the code snippet here
For more flexibility, you can store your custom theme colors in a map and generate theme classes dynamically:
$customthemes: (
"theme1": purple,
"theme2": cyan,
"theme3": orange
);
@each $themeName, $color in $customthemes {
.#{$themeName} {
@include build-primary-classes($color);
}
}
Explore the dynamic theme generation here
If you're using Webpack, you can pass the $customthemes map to the extract-text-webpack-plugin and SASS-loader for efficient styling. Simply include the $customthemes data using the 'data' option:
webpack-config:
....
use: extractSass.extract({
use: [
{
loader: "sass-loader",
options: {
allChunks: true,
data: '$customthemes:("theme1":purple,"theme2":pink,"theme3":red);'
}
}]
})
.....
Keep in mind that having too many custom themes may lead to large CSS files. Consider generating separate theme.css
files with SASS and including them as needed in the HTML HEAD section.
Related Resources:
How to customize Bootstrap 4 with SASS
Changing the Bootstrap primary color