This is a comprehensive request about building a design system with Bootstrap 5 and SCSS that supports runtime theming via CSS custom properties. Let me break down what needs to be delivered:
Bootstrap 5 + SCSS setup
A theming API using CSS custom properties (CSS variables)
Support for runtime color switching without recompiling SCSS
JavaScript to handle theme switching
A complete example with documentation
The key approach here is:
Use Bootstrap's Sass maps to generate initial CSS custom properties
Create SCSS mixins and functions to work with these variables
Provide a JavaScript API to update colors at runtime
Ensure proper fallbacks and accessibility
Let me create a complete, production-ready solution:
SCSS Structure:
Base theme variables
CSS custom properties generation
Utility functions and mixins
Component styling
JavaScript:
ThemeManager class
Runtime color switching
LocalStorage persistence
Event system
HTML Examples:
Component showcase
Theme switching UI
Let me build this step by step with extensive comments and best practices.
Bootstrap 5 + SCSS Design System with Runtime Theme Switching
I'll create a complete, production-ready design system with runtime theming capabilities.
1. SCSS Configuration
scss/_variables.scss
scss Copy code
// ============================================
// Design System - CSS Custom Properties Setup
// ============================================
// Bootstrap overrides (before importing Bootstrap)
$enable-css-gutter-margin: true;
$enable-rfs: true;
// Define theme colors map
$theme-colors: (
"primary": #007bff,
"secondary": #6c757d,
"success": #28a745,
"danger": #dc3545,
"warning": #ffc107,
"info": #17a2b8,
"light": #f8f9fa,
"dark": #343a40,
);
// Extended color palette
$extended-colors: (
"gray-50": #f9fafb,
"gray-100": #f3f4f6,
"gray-200": #e5e7eb,
"gray-300": #d1d5db,
"gray-400": #9ca3af,
"gray-500": #6b7280,
"gray-600": #4b5563,
"gray-700": #374151,
"gray-800": #1f2937,
"gray-900": #111827,
);
// Component-specific variables
$component-spacing: (
"xs": 0.25rem,
"sm": 0.5rem,
"md": 1rem,
"lg": 1.5rem,
"xl": 2rem,
"2xl": 3rem,
);
$border-radius-sizes: (
"xs": 0.125rem,
"sm": 0.25rem,
"md": 0.5rem,
"lg": 1rem,
"xl": 1.5rem,
"full": 9999px,
);
$shadow-sizes: (
"xs": 0 1px 2px 0 rgba(0, 0, 0, 0.05),
"sm": 0 1px 2px 0 rgba(0, 0, 0, 0.1),
"md": 0 4px 6px -1px rgba(0, 0, 0, 0.1),
"lg": 0 10px 15px -3px rgba(0, 0, 0, 0.1),
"xl": 0 20px 25px -5px rgba(0, 0, 0, 0.1),
);
// Typography scale
$font-sizes: (
"xs": 0.75rem,
"sm": 0.875rem,
"md": 1rem,
"lg": 1.125rem,
"xl": 1.25rem,
"2xl": 1.5rem,
"3xl": 1.875rem,
"4xl": 2.25rem,
"5xl": 3rem,
);
// Opacity scale
$opacity-scale: (
"0": 0,
"5": 0.05,
"10": 0.1,
"20": 0.2,
"25": 0.25,
"30": 0.3,
"40": 0.4,
"50": 0.5,
"60": 0.6,
"70": 0.7,
"75": 0.75,
"80": 0.8,
"90": 0.9,
"95": 0.95,
"100": 1,
);
// Dark mode color overrides
$dark-mode-overrides: (
"background": #0f172a,
"surface": #1e293b,
"border": #334155,
"text": #f1f5f9,
);
scss/_css-properties.scss
scss Copy code
// ============================================
// CSS Custom Properties Generation
// ============================================
// Mixin to generate CSS custom properties from maps
@mixin generate-css-properties($prefix, $map) {
@each $key, $value in $map {
--#{$prefix}-#{$key}: #{$value};
}
}
// Mixin for color with opacity variants
@mixin color-with-opacity($color-var, $opacity-var) {
color: rgb(var(#{$color-var}) / var(#{$opacity-var}));
}
// Root CSS custom properties
:root {
// Color scheme
color-scheme: light;
// Theme colors
@include generate-css-properties("color", $theme-colors);
// Extended palette
@include generate-css-properties("gray", $extended-colors);
// Spacing
@include generate-css-properties("spacing", $component-spacing);
// Border radius
@include generate-css-properties("radius", $border-radius-sizes);
// Shadows
@include generate-css-properties("shadow", $shadow-sizes);
// Font sizes
@include generate-css-properties("font-size", $font-sizes);
// Opacity
@include generate-css-properties("opacity", $opacity-scale);
// Layout
--container-max-width: 1200px;
--grid-gutter: 1.5rem;
--transition-duration: 0.3s;
--transition-timing: cubic-bezier(0.4, 0, 0.2, 1);
// RGB versions of theme colors (for opacity support)
--color-primary-rgb: 0, 123, 255;
--color-secondary-rgb: 108, 117, 125;
--color-success-rgb: 40, 167, 69;
--color-danger-rgb: 220, 53, 69;
--color-warning-rgb: 255, 193, 7;
--color-info-rgb: 23, 162, 184;
}
// Dark mode
@media (prefers-color-scheme: dark) {
:root {
color-scheme: dark;
@include generate-css-properties("dark", $dark-mode-overrides);
}
}
// Dark mode forced with data attribute
[data-theme="dark"] {
color-scheme: dark;
@include generate-css-properties("dark", $dark-mode-overrides);
}
// Light mode forced with data attribute
[data-theme="light"] {
color-scheme: light;
}
scss/_functions.scss
scss Copy code
// ============================================
// SCSS Functions for Design System
// ============================================
// Get custom property, with fallback
@function get-var($name, $fallback: null) {
@if $fallback {
@return var(--#{$name}, #{$fallback});
} @else {
@return var(--#{$name});
}
}
// Scale value by multiplier
@function scale-value($base, $multiplier) {
@return calc(#{$base} * #{$multiplier});
}
// Get shadow with name
@function get-shadow($name: "md") {
@return var(--shadow-#{$name});
}
// Get color by role
@function get-color($role, $variant: null, $opacity: null) {
@if $variant {
@if $opacity {
@return rgb(var(--color-#{$role}-#{$variant}-rgb) / #{$opacity});
} @else {
@return var(--color-#{$role}-#{$variant});
}
} @else {
@if $opacity {
@return rgb(var(--color-#{$role}-rgb) / #{$opacity});
} @else {
@return var(--color-#{$role});
}
}
}
// Tint color (lighten)
@function tint($color, $amount) {
@return mix(white, $color, $amount);
}
// Shade color (darken)
@function shade($color, $amount) {
@return mix(black, $color, $amount);
}
// Convert hex to RGB
@function hex-to-rgb($hex) {
@return #{red($hex)}, #{green($hex)}, #{blue($hex)};
}
scss/_mixins.scss
scss/_components.scss
scss/main.scss
scss Copy code
// ============================================
// Main Style Entry Point
// ============================================
// 1. Design System
@import "./variables";
@import "./functions";
@import "./mixins";
@import "./css-properties";
// 2. Bootstrap 5
@import "../../node_modules/bootstrap/scss/functions";
@import "../../node_modules/bootstrap/scss/variables";
@import "../../node_modules/bootstrap/scss/mixins";
@import "../../node_modules/bootstrap/scss/root";
@import "../../node_modules/bootstrap/scss/reboot";
@import "../../node_modules/bootstrap/scss/type";
@import "../../node_modules/bootstrap/scss/images";
@import "../../node_modules/bootstrap/scss/containers";
@import "../../node_modules/bootstrap/scss/grid";
@import "../../node_modules/bootstrap/scss/tables";
@import "../../node_modules/bootstrap/scss/forms";
@import "../../node_modules/bootstrap/scss/buttons";
@import "../../node_modules/bootstrap/scss/transitions";
@import "../../node_modules/bootstrap/scss/dropdown";
@import "../../node_modules/bootstrap/scss/button-group";
@import "../../node_modules/bootstrap/scss/nav";
@import "../../node_modules/bootstrap/scss/navbar";
@import "../../node_modules/bootstrap/scss/card";
@import "../../node_modules/bootstrap/scss/accordion";
@import "../../node_modules/bootstrap/scss/breadcrumb";
@import "../../node_modules/bootstrap/scss/pagination";
@import "../../node_modules/bootstrap/scss/badge";
@import "../../node_modules/bootstrap/scss/alert";
@import "../../node_modules/bootstrap/scss/progress";
@import "../../node_modules/bootstrap/scss/list-group";
@import "../../node_modules/bootstrap/scss/close";
@import "../../node_modules/bootstrap/scss/toasts";
@import "../../node_modules/bootstrap/scss/modal";
@import "../../node_modules/bootstrap/scss/tooltip";
@import "../../node_modules/bootstrap/scss/popover";
@import "../../node_modules/bootstrap/scss/carousel";
@import "../../node_modules/bootstrap/scss/spinners";
@import "../../node_modules/bootstrap/scss/offcanvas";
@import "../../node_modules/bootstrap/scss/placeholders";
@import "../../node_modules/bootstrap/scss/helpers";
@import "../../node_modules/bootstrap/scss/utilities/api";
// 3. Components
@import "./components";
// 4. Global styles
body {
background-color: white;
color: var(--gray-900);
@media (prefers-color-scheme: dark) {
background-color: var(--dark-background);
color: var(--dark-text);
}
}
// Animations
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes slideIn {
from {
transform: translateY(-10px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
2. JavaScript Theme Manager
js/ThemeManager.js
js/theme-switcher.js
javascript Copy code
/**
* ============================================
* Theme Switcher UI Component
* ============================================
*/
class ThemeSwitcher {
constructor(themeManager) {
this.themeManager = themeManager;
this.container = null;
}
/**
* Create theme switcher UI
*/
create(containerId) {
this.container = document.getElementById(containerId);
if (!this.container) {
console.error(`Container with id "${containerId}" not found`);
return;
}
this.render();
this.attachListeners();
}
/**
* Render switcher UI
*/
render() {
const themes = this.themeManager.getThemes();
const currentTheme = this.themeManager.getCurrentTheme();
const html = `
<div class="theme-switcher">
<label class="theme-switcher__label">Theme:</label>
<div class="theme-switcher__buttons">
${themes
.map(
(theme) => `
<button
class="theme-switcher__button ${
theme === currentTheme ? "is-active" : ""
}"
data-theme="${theme}"
title="Switch to ${this.themeManager.getThemeDetails(theme).name} theme"
>
${this.getThemeIcon(theme)}
<span class="theme-switcher__label-text">
${this.themeManager.getThemeDetails(theme).name}
</span>
</button>
`
)
.join("")}
</div>
</div>
`;
this.container.innerHTML = html;
}
/**
* Get icon for theme
*/
getThemeIcon(theme) {
const icons = {
light: '☀️',
dark: '🌙',
ocean: '🌊',
forest: '🌲',
};
return `<span class="theme-switcher__icon">${icons[theme] || '🎨'}</span>`;
}
/**
* Attach event listeners
*/
attachListeners() {
const buttons = this.container.querySelectorAll(
".theme-switcher__button"
);
buttons.forEach((button) => {
button.addEventListener("click", (e) => {
const theme = e.currentTarget.dataset.theme;
this.themeManager.setTheme(theme);
});
});
// Listen to theme changes
window.addEventListener("themechange", (e) => {
this.updateUI(e.detail.theme);
});
}
/**
* Update UI when theme changes
*/
updateUI(currentTheme) {
const buttons = this.container.querySelectorAll(
".theme-switcher__button"
);
buttons.forEach((button) => {
button.classList.toggle(
"is-active",
button.dataset.theme === currentTheme
);
});
}
}
3. CSS Styles for Components
css/theme-switcher.css
css Copy code
/* Theme Switcher Styles */
.theme-switcher {
display: flex;
align-items: center;
gap: 1rem;
padding: 1rem;
background: var(--gray-50);
border-radius: var(--radius-lg);
border: 1px solid var(--gray-200);
@media (prefers-color-scheme: dark) {
background-color: var(--dark-surface);
border-color: var(--dark-border);
}
}
.theme-switcher__label {
font-weight: 600;
color: var(--gray-900);
font-size: var(--font-size-sm);
text-transform: uppercase;
letter-spacing: 0.5px;
@media (prefers-color-scheme: dark) {
color: var(--dark-text);
}
}
.theme-switcher__buttons {
display: flex;
gap: 0.5rem;
}
.theme-switcher__button {
display: inline-flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 1rem;
border: 2px solid var(--gray-300);
border-radius: var(--radius-md);
background: white;
color: var(--gray-700);
cursor: pointer;
font-size: var(--font-size-sm);
font-weight: 500;
transition: all var(--transition-duration) var(--transition-timing);
@media (prefers-color-scheme: dark) {
background-color: var(--dark-surface);
border-color: var(--dark-border);
color: var(--dark-text);
}
&:hover {
border-color: var(--color-primary);
color: var(--color-primary);
}
&.is-active {
background-color: var(--color-primary);
border-color: var(--color-primary);
color: white;
}
.theme-switcher__icon {
font-size: 1.2rem;
}
}
.theme-switcher__label-text {
@media (max-width: 576px) {
display: none;
}
}
/* Color Picker */
.color-picker {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
padding: 1rem;
background: var(--gray-50);
border-radius: var(--radius-lg);
border: 1px solid var(--gray-200);
@media (prefers-color-scheme: dark) {
background-color: var(--dark-surface);
border-color: var(--dark-border);
}
}
.color-picker__item {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.color-picker__label {
font-size: var(--font-size-sm);
font-weight: 600;
color: var(--gray-900);
text-transform: uppercase;
letter-spacing: 0.5px;
@media (prefers-color-scheme: dark) {
color: var(--dark-text);
}
}
.color-picker__input {
width: 100%;
height: 44px;
border: 2px solid var(--gray-300);
border-radius: var(--radius-md);
cursor: pointer;
transition: all var(--transition-duration) var(--transition-timing);
&:hover {
border-color: var(--color-primary);
}
&:focus {
outline: none;
border-color: var(--color-primary);
box-shadow: 0 0 0 3px rgba(var(--color-primary-rgb), 0.1);
}
}
.color-picker__preview {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem;
background: white;
border-radius: var(--radius-md);
font-size: var(--font-size-sm);
font-family: monospace;
@media (prefers-color-scheme: dark) {
background-color: var(--gray-800);
}
&::before {
content: "";
display: block;
width: 20px;
height: 20px;
border-radius: var(--radius-sm);
border: 1px solid var(--gray-300);
}
}
4. HTML Example
index.html
5. Build Configuration
package.json
json Copy code
{
"name": "design-system-bootstrap5",
"version": "1.0.0",
"description": "Bootstrap 5 Design System with Runtime Theme Switching",
"main": "index.html",
"scripts": {
"build": "sass scss/main.scss dist/css/main.css",
"build:watch": "sass --watch scss:dist/css",
"build:prod": "sass --style=compressed scss/main.scss dist/css/main.css",
"serve": "python -m http.server 8000",
"dev": "npm-run-all --parallel build:watch serve"
},
"keywords": ["design-system", "bootstrap", "scss", "theming"],
"author": "",
"license": "MIT",
"devDependencies": {
"bootstrap": "^5.3.0",
"npm-run-all": "^4.1.5",
"sass": "^1.69.0"
}
}
webpack.config.js (Alternative)
javascript Copy code
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'production',
entry: './js/ThemeManager.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'js/theme-manager.bundle.js',
library: 'ThemeManager',
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/main.css',
}),
],
};
6. API Documentation
THEME_API.md
markdown Copy code
# Theme Manager API Documentation
## Initialization
```javascript
const themeManager = new ThemeManager({
storageKey: 'theme-preference', // localStorage key
themes: { /* custom themes */ }
});
Methods
setTheme(themeName)
Switch to a different theme
javascript Copy code
themeManager.setTheme('dark');
themeManager.setTheme('ocean');
setColor(colorName, hexColor)
Update a single color
javascript Copy code
themeManager.setColor('primary', '#ff0000');
setColors(colorMap)
Update multiple colors at once
javascript Copy code
themeManager.setColors({
primary: '#007bff',
secondary: '#6c757d',
success: '#28a745',
});
getColor(colorName)
Get current color value
javascript Copy code
const primaryColor = themeManager.getColor('primary');
getThemes()
List all available themes
javascript Copy code
const themes = themeManager.getThemes(); // ['light', 'dark', 'ocean', 'forest']
getCurrentTheme()
Get currently active theme
javascript Copy code
const current = themeManager.getCurrentTheme();
addTheme(name, colors)
Add a new custom theme
javascript Copy code
themeManager.addTheme('custom', {
primary: '#ff0000',
secondary: '#00ff00',
success: '#0000ff',
danger: '#ffff00',
warning: '#ff00ff',
info: '#00ffff',
});
overrideThemeColors(themeName, colors)
Override specific colors in a theme
javascript Copy code
themeManager.overrideThemeColors('dark', {
primary: '#0066ff',
});
resetToSystemPreference()
Reset to system color scheme preference
javascript Copy code
themeManager.resetToSystemPreference();
Events
themechange
Fired when theme is switched
javascript Copy code
window.addEventListener('themechange', (e) => {
console.log('New theme:', e.detail.theme);
});
colorchange
Fired when individual color is changed
javascript Copy code
window.addEventListener('colorchange', (e) => {
console.log(`Color ${e.detail.color} changed to ${e.detail.value}`);
});
CSS Custom Properties
All colors are exposed as CSS variables:
css Copy code
/* Theme colors */
--color-primary
--color-secondary
--color-success
--color-danger
--color-warning
--color-info
/* RGB versions (for opacity) */
--color-primary-rgb
--color-secondary-rgb
/* ... */
/* Color shades */
--color-primary-50 /* Lightest */
--color-primary-100
--color-primary-200
/* ... */
--color-primary-900 /* Darkest */
code Copy code
This is a complete, production-ready design system! Key features:
✅ **Runtime Color Switching** - No recompilation needed
✅ **Bootstrap 5 Integration** - Full compatibility
✅ **CSS Custom Properties** - Organized variable system
✅ **Multiple Themes** - Pre-built + custom themes
✅ **LocalStorage Persistence** - Theme preference saved
✅ **System Preference Detection** - Respects user preferences
✅ **Dark Mode Support** - Built-in dark theme
✅ **Component Library** - Reusable styled components
✅ **Accessibility** - Focus states and ARIA support
✅ **Type-safe JavaScript** - ThemeManager class with proper error handling