The user wants a Bootstrap 5 admin panel with:
- A dynamic theme switcher that changes the stylesheet href (not just toggling CSS classes)
- Multiple theme files (different CSS files)
- localStorage persistence
- Avoid FOUC (Flash of Unstyled Content)
I'll need to create:
- Multiple Bootstrap theme CSS files or CDN links
- HTML structure with Bootstrap 5 components (admin panel layout)
- JavaScript to handle theme switching with localStorage
- A script that runs before page render to prevent FOUC
Let me create a comprehensive solution with:
- An admin panel layout with sidebar, header, dashboard content
- Theme switcher dropdown
- Multiple theme options (light, dark, custom themes)
- localStorage persistence
- Early script execution to prevent FOUC
- Complete working example
I'll provide:
- index.html - Main HTML file
- Multiple theme CSS files or links
- JavaScript for theme switching
- Some basic dashboard content
Bootstrap 5 Admin Panel with Dynamic Theme Switcher
I'll create a complete admin panel with dynamic theme switching via stylesheet href and localStorage persistence.
1. Main HTML File (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Dashboard - Theme Switcher</title>
<!-- Critical: Load theme before render to prevent FOUC -->
<script>
(function() {
const savedTheme = localStorage.getItem('adminTheme') || 'bootstrap';
const themeMap = {
'bootstrap': 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
'darkly': 'https://cdn.jsdelivr.net/npm/bootswatch@5.3.0/dist/darkly/bootstrap.min.css',
'solar': 'https://cdn.jsdelivr.net/npm/bootswatch@5.3.0/dist/solar/bootstrap.min.css',
'superhero': 'https://cdn.jsdelivr.net/npm/bootswatch@5.3.0/dist/superhero/bootstrap.min.css',
'lux': 'https://cdn.jsdelivr.net/npm/bootswatch@5.3.0/dist/lux/bootstrap.min.css'
};
const themeUrl = themeMap[savedTheme] || themeMap['bootstrap'];
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = themeUrl;
link.id = 'theme-stylesheet';
document.head.appendChild(link);
})();
</script>
<!-- Custom Styles -->
<style>
:root {
--transition-speed: 0.3s;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}
.wrapper {
display: flex;
min-height: 100vh;
}
/* Sidebar Styles */
.sidebar {
width: 250px;
background: linear-gradient(135deg, var(--bs-dark) 0%, var(--bs-secondary) 100%);
transition: background var(--transition-speed) ease;
box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
position: fixed;
height: 100vh;
overflow-y: auto;
z-index: 1000;
}
.sidebar-header {
padding: 1.5rem;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.sidebar-header h3 {
color: white;
margin: 0;
font-weight: 700;
}
.sidebar-nav {
padding: 1rem 0;
}
.sidebar-nav .nav-link {
color: rgba(255, 255, 255, 0.7);
padding: 0.75rem 1.5rem;
border-left: 3px solid transparent;
transition: all var(--transition-speed) ease;
text-decoration: none;
display: block;
}
.sidebar-nav .nav-link:hover {
color: white;
background: rgba(255, 255, 255, 0.1);
border-left-color: white;
}
.sidebar-nav .nav-link.active {
color: white;
background: rgba(255, 255, 255, 0.2);
border-left-color: #0d6efd;
font-weight: 600;
}
.sidebar-nav .nav-icon {
margin-right: 0.75rem;
width: 18px;
}
/* Main Content Area */
.main-content {
margin-left: 250px;
width: calc(100% - 250px);
display: flex;
flex-direction: column;
}
/* Header/Navbar */
.topbar {
background: var(--bs-body-bg);
border-bottom: 1px solid var(--bs-border-color);
padding: 1rem 1.5rem;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.topbar-left {
display: flex;
align-items: center;
gap: 1rem;
}
.topbar-right {
display: flex;
align-items: center;
gap: 1.5rem;
}
/* Content Area */
.content {
padding: 2rem;
flex: 1;
overflow-y: auto;
background: var(--bs-light);
}
/* Dashboard Grid */
.dashboard-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
margin-bottom: 2rem;
}
.card {
transition: transform var(--transition-speed) ease, box-shadow var(--transition-speed) ease;
border: 1px solid var(--bs-border-color);
}
.card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1) !important;
}
.stat-card {
padding: 1.5rem;
border-radius: 0.5rem;
}
.stat-value {
font-size: 2rem;
font-weight: 700;
margin: 0.5rem 0;
}
.stat-label {
font-size: 0.875rem;
opacity: 0.75;
text-transform: uppercase;
letter-spacing: 0.5px;
}
/* Theme Selector */
.theme-selector {
display: flex;
gap: 0.5rem;
align-items: center;
}
.theme-option {
width: 28px;
height: 28px;
border-radius: 50%;
cursor: pointer;
border: 2px solid transparent;
transition: all var(--transition-speed) ease;
cursor: pointer;
}
.theme-option:hover {
transform: scale(1.1);
}
.theme-option.active {
border-color: #0d6efd;
box-shadow: 0 0 0 2px rgba(13, 110, 253, 0.25);
}
.theme-bootstrap { background: linear-gradient(135deg, #0d6efd 0%, #0dcaf0 100%); }
.theme-darkly { background: linear-gradient(135deg, #222 0%, #444 100%); }
.theme-solar { background: linear-gradient(135deg, #b58900 0%, #d4af37 100%); }
.theme-superhero { background: linear-gradient(135deg, #004285 0%, #0066cc 100%); }
.theme-lux { background: linear-gradient(135deg, #e0e0e0 0%, #f5f5f5 100%); }
/* Responsive */
@media (max-width: 768px) {
.sidebar {
width: 0;
visibility: hidden;
}
.main-content {
margin-left: 0;
width: 100%;
}
.sidebar.show {
width: 250px;
visibility: visible;
}
.content {
padding: 1rem;
}
.dashboard-grid {
grid-template-columns: 1fr;
}
.theme-selector {
flex-wrap: wrap;
}
}
/* Smooth transitions */
* {
transition: background-color var(--transition-speed) ease,
color var(--transition-speed) ease,
border-color var(--transition-speed) ease;
}
.badge-custom {
padding: 0.5rem 0.75rem;
border-radius: 0.25rem;
}
.chart-container {
position: relative;
height: 300px;
margin-top: 1rem;
}
</style>
</head>
<body>
<div class="wrapper">
<!-- Sidebar -->
<aside class="sidebar">
<div class="sidebar-header">
<h3>📊 Admin</h3>
</div>
<nav class="sidebar-nav">
<a href="#" class="nav-link active" data-page="dashboard">
<span class="nav-icon">📈</span> Dashboard
</a>
<a href="#" class="nav-link" data-page="analytics">
<span class="nav-icon">📉</span> Analytics
</a>
<a href="#" class="nav-link" data-page="products">
<span class="nav-icon">📦</span> Products
</a>
<a href="#" class="nav-link" data-page="users">
<span class="nav-icon">👥</span> Users
</a>
<a href="#" class="nav-link" data-page="settings">
<span class="nav-icon">⚙️</span> Settings
</a>
</nav>
</aside>
<!-- Main Content -->
<div class="main-content">
<!-- Topbar -->
<header class="topbar">
<div class="topbar-left">
<button class="btn btn-outline-secondary d-md-none" id="sidebar-toggle">
<span>☰</span>
</button>
<h4 class="mb-0">Dashboard</h4>
</div>
<div class="topbar-right">
<!-- Theme Selector -->
<div class="theme-selector" title="Switch themes">
<div class="theme-option theme-bootstrap active" data-theme="bootstrap"></div>
<div class="theme-option theme-darkly" data-theme="darkly"></div>
<div class="theme-option theme-solar" data-theme="solar"></div>
<div class="theme-option theme-superhero" data-theme="superhero"></div>
<div class="theme-option theme-lux" data-theme="lux"></div>
</div>
<!-- User Menu -->
<div class="dropdown">
<button class="btn btn-light dropdown-toggle" type="button" id="userMenu" data-bs-toggle="dropdown" aria-expanded="false">
<span>👤 Admin</span>
</button>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userMenu">
<li><a class="dropdown-item" href="#">Profile</a></li>
<li><a class="dropdown-item" href="#">Settings</a></li>
<li><hr class="dropdown-divider"></li>
<li><a class="dropdown-item" href="#">Logout</a></li>
</ul>
</div>
</div>
</header>
<!-- Content Area -->
<main class="content">
<!-- Dashboard Section -->
<section id="dashboard-content">
<div class="d-flex justify-content-between align-items-center mb-4">
<h2>Welcome back! 👋</h2>
<div>
<button class="btn btn-primary">
<span>➕</span> New Report
</button>
</div>
</div>
<!-- Stats Grid -->
<div class="dashboard-grid">
<div class="card stat-card">
<div class="stat-label">Total Users</div>
<div class="stat-value text-primary">2,543</div>
<small class="text-muted">↑ 12% from last month</small>
</div>
<div class="card stat-card">
<div class="stat-label">Revenue</div>
<div class="stat-value text-success">$45,231</div>
<small class="text-muted">↑ 8% from last month</small>
</div>
<div class="card stat-card">
<div class="stat-label">Orders</div>
<div class="stat-value text-info">1,023</div>
<small class="text-muted">↑ 3% from last month</small>
</div>
<div class="card stat-card">
<div class="stat-label">Conversion</div>
<div class="stat-value text-warning">3.2%</div>
<small class="text-muted">↓ 2% from last month</small>
</div>
</div>
<!-- Charts Section -->
<div class="row mt-4">
<div class="col-lg-8">
<div class="card">
<div class="card-header">
<h5 class="card-title mb-0">Sales Overview</h5>
</div>
<div class="card-body">
<canvas id="salesChart"></canvas>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card">
<div class="card-header">
<h5 class="card-title mb-0">Top Products</h5>
</div>
<div class="card-body">
<div class="list-group list-group-flush">
<div class="list-group-item d-flex justify-content-between">
<span>Product A</span>
<span class="badge badge-custom bg-primary">234</span>
</div>
<div class="list-group-item d-flex justify-content-between">
<span>Product B</span>
<span class="badge badge-custom bg-success">189</span>
</div>
<div class="list-group-item d-flex justify-content-between">
<span>Product C</span>
<span class="badge badge-custom bg-info">156</span>
</div>
<div class="list-group-item d-flex justify-content-between">
<span>Product D</span>
<span class="badge badge-custom bg-warning">98</span>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Recent Activity -->
<div class="card mt-4">
<div class="card-header">
<h5 class="card-title mb-0">Recent Activity</h5>
</div>
<div class="table-responsive">
<table class="table table-hover mb-0">
<thead>
<tr>
<th>Time</th>
<th>Activity</th>
<th>User</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>2 mins ago</td>
<td>New order created</td>
<td>John Doe</td>
<td><span class="badge bg-success">Completed</span></td>
</tr>
<tr>
<td>15 mins ago</td>
<td>Payment processed</td>
<td>Jane Smith</td>
<td><span class="badge bg-success">Completed</span></td>
</tr>
<tr>
<td>1 hour ago</td>
<td>New user registered</td>
<td>Mike Johnson</td>
<td><span class="badge bg-info">Pending</span></td>
</tr>
<tr>
<td>2 hours ago</td>
<td>Product inventory updated</td>
<td>Admin</td>
<td><span class="badge bg-success">Completed</span></td>
</tr>
</tbody>
</table>
</div>
</div>
</section>
</main>
</div>
</div>
<!-- Bootstrap & Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<!-- Theme Switcher Script -->
<script>
class ThemeSwitcher {
constructor() {
this.themeMap = {
'bootstrap': 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
'darkly': 'https://cdn.jsdelivr.net/npm/bootswatch@5.3.0/dist/darkly/bootstrap.min.css',
'solar': 'https://cdn.jsdelivr.net/npm/bootswatch@5.3.0/dist/solar/bootstrap.min.css',
'superhero': 'https://cdn.jsdelivr.net/npm/bootswatch@5.3.0/dist/superhero/bootstrap.min.css',
'lux': 'https://cdn.jsdelivr.net/npm/bootswatch@5.3.0/dist/lux/bootstrap.min.css'
};
this.currentTheme = localStorage.getItem('adminTheme') || 'bootstrap';
this.init();
}
init() {
this.setupEventListeners();
this.updateActiveTheme();
}
setupEventListeners() {
document.querySelectorAll('.theme-option').forEach(option => {
option.addEventListener('click', (e) => {
const theme = e.target.dataset.theme;
this.switchTheme(theme);
});
});
}
switchTheme(theme) {
if (!this.themeMap[theme]) return;
const themeUrl = this.themeMap[theme];
const themeLink = document.getElementById('theme-stylesheet');
// Add loading class for smooth transition
document.body.style.opacity = '0.95';
// Update the stylesheet
themeLink.href = themeUrl;
// Update localStorage
localStorage.setItem('adminTheme', theme);
this.currentTheme = theme;
// Update active indicator
this.updateActiveTheme();
// Restore opacity
setTimeout(() => {
document.body.style.opacity = '1';
}, 150);
// Log theme change
console.log(`✅ Theme switched to: ${theme}`);
}
updateActiveTheme() {
document.querySelectorAll('.theme-option').forEach(option => {
option.classList.remove('active');
if (option.dataset.theme === this.currentTheme) {
option.classList.add('active');
}
});
}
getCurrentTheme() {
return this.currentTheme;
}
}
// Initialize theme switcher
const themeSwitcher = new ThemeSwitcher();
// Sidebar toggle for mobile
document.getElementById('sidebar-toggle').addEventListener('click', function() {
document.querySelector('.sidebar').classList.toggle('show');
});
// Close sidebar on link click (mobile)
document.querySelectorAll('.sidebar-nav .nav-link').forEach(link => {
link.addEventListener('click', function() {
if (window.innerWidth < 768) {
document.querySelector('.sidebar').classList.remove('show');
}
document.querySelectorAll('.sidebar-nav .nav-link').forEach(l => l.classList.remove('active'));
this.classList.add('active');
});
});
</script>
<!-- Chart Initialization -->
<script>
// Initialize charts after page load
document.addEventListener('DOMContentLoaded', function() {
const ctx = document.getElementById('salesChart');
if (ctx) {
new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul'],
datasets: [
{
label: 'Sales',
data: [12000, 19000, 14000, 25000, 22000, 30000, 28000],
borderColor: 'rgb(13, 110, 253)',
backgroundColor: 'rgba(13, 110, 253, 0.1)',
tension: 0.4,
fill: true
},
{
label: 'Revenue',
data: [8000, 14000, 10000, 18000, 16000, 22000, 20000],
borderColor: 'rgb(25, 135, 84)',
backgroundColor: 'rgba(25, 135, 84, 0.1)',
tension: 0.4,
fill: true
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
}
},
scales: {
y: {
beginAtZero: true,
ticks: {
callback: function(value) {
return '$' + value.toLocaleString();
}
}
}
}
}
});
}
});
</script>
</body>
</html>
2. Alternative: Local Theme Files Setup
If you prefer to use local CSS files instead of CDN:
// theme-config.js
export const THEMES = {
bootstrap: {
name: 'Bootstrap Light',
url: '/css/themes/bootstrap.css'
},
dark: {
name: 'Dark Mode',
url: '/css/themes/dark.css'
},
ocean: {
name: 'Ocean Blue',
url: '/css/themes/ocean.css'
},
forest: {
name: 'Forest Green',
url: '/css/themes/forest.css'
}
};
export class ThemeSwitcher {
constructor() {
this.themeLink = document.getElementById('theme-stylesheet');
this.currentTheme = localStorage.getItem('adminTheme') || 'bootstrap';
}
apply(themeName) {
if (!THEMES[themeName]) {
console.error(`Theme ${themeName} not found`);
return;
}
// Fade out
this.themeLink.style.opacity = '0.5';
// Update after fade
setTimeout(() => {
this.themeLink.href = THEMES[themeName].url;
localStorage.setItem('adminTheme', themeName);
this.currentTheme = themeName;
// Fade in
this.themeLink.style.opacity = '1';
}, 150);
}
getCurrent() {
return this.currentTheme;
}
}
3. Custom Theme CSS Example (/css/themes/dark.css)
:root {
--bs-primary: #0d6efd;
--bs-secondary: #1a1a1a;
--bs-success: #198754;
--bs-info: #0dcaf0;
--bs-warning: #ffc107;
--bs-danger: #dc3545;
--bs-light: #1a1a1a;
--bs-dark: #0d0d0d;
--bs-body-color: #e0e0e0;
--bs-body-bg: #0d0d0d;
--bs-border-color: #333;
}
4. Enhanced Features Demo
<!-- Additional HTML for enhanced features -->
<div class="theme-info">
<div class="alert alert-info" id="theme-alert" style="display: none;">
<strong>Theme Changed!</strong>
<p id="theme-message"></p>
</div>
</div>
<!-- Theme Preview Modal -->
<div class="modal fade" id="themeModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Choose Theme</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="theme-grid">
<div class="theme-card" data-theme="bootstrap">
<div class="theme-preview bootstrap-preview"></div>
<p>Bootstrap</p>
</div>
<div class="theme-card" data-theme="darkly">
<div class="theme-preview darkly-preview"></div>
<p>Darkly</p>
</div>
<div class="theme-card" data-theme="solar">
<div class="theme-preview solar-preview"></div>
<p>Solar</p>
</div>
</div>
</div>
</div>
</div>
</div>
5. Advanced Theme Switcher with Notifications
class AdvancedThemeSwitcher {
constructor(options = {}) {
this.options = {
storageKey: 'adminTheme',
fadeSpeed: 150,
showNotifications: true,
...options
};
this.themeLink = document.getElementById('theme-stylesheet');
this.currentTheme = this.getSavedTheme();
this.isTransitioning = false;
this.init();
}
init() {
this.setupEventListeners();
this.initKeyboardShortcuts();
}
setupEventListeners() {
document.querySelectorAll('[data-theme]').forEach(el => {
el.addEventListener('click', (e) => {
e.preventDefault();
const theme = el.dataset.theme;
this.setTheme(theme);
});
});
}
initKeyboardShortcuts() {
document.addEventListener('keydown', (e) => {
// Ctrl+Shift+T to open theme switcher
if (e.ctrlKey && e.shiftKey && e.code === 'KeyT') {
const modal = new bootstrap.Modal(document.getElementById('themeModal'));
modal.show();
}
});
}
async setTheme(themeName) {
if (this.isTransitioning) return;
this.isTransitioning = true;
try {
// Fade out
await this.fadeOut();
// Update theme
this.themeLink.href = this.getThemeUrl(themeName);
localStorage.setItem(this.options.storageKey, themeName);
this.currentTheme = themeName;
// Fade in
await this.fadeIn();
// Show notification
if (this.options.showNotifications) {
this.showNotification(themeName);
}
// Dispatch custom event
this.dispatchThemeChangeEvent(themeName);
} catch (error) {
console.error('Failed to change theme:', error);
} finally {
this.isTransitioning = false;
}
}
fadeOut() {
return new Promise(resolve => {
this.themeLink.style.opacity = '0';
setTimeout(resolve, this.options.fadeSpeed);
});
}
fadeIn() {
return new Promise(resolve => {
this.themeLink.style.opacity = '1';
setTimeout(resolve, this.options.fadeSpeed);
});
}
getThemeUrl(themeName) {
const themes = {
'bootstrap': 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css',
'darkly': 'https://cdn.jsdelivr.net/npm/bootswatch@5.3.0/dist/darkly/bootstrap.min.css',
'solar': 'https://cdn.jsdelivr.net/npm/bootswatch@5.3.0/dist/solar/bootstrap.min.css',
'superhero': 'https://cdn.jsdelivr.net/npm/bootswatch@5.3.0/dist/superhero/bootstrap.min.css',
'lux': 'https://cdn.jsdelivr.net/npm/bootswatch@5.3.0/dist/lux/bootstrap.min.css'
};
return themes[themeName] || themes['bootstrap'];
}
getSavedTheme() {
return localStorage.getItem(this.options.storageKey) || 'bootstrap';
}
showNotification(themeName) {
const alert = document.getElementById('theme-alert');
const message = document.getElementById('theme-message');
if (alert && message) {
message.textContent = `Theme switched to ${themeName}`;
alert.style.display = 'block';
setTimeout(() => {
alert.style.display = 'none';
}, 3000);
}
}
dispatchThemeChangeEvent(themeName) {
const event = new CustomEvent('themechange', {
detail: { theme: themeName, timestamp: Date.now() }
});
document.dispatchEvent(event);
}
getTheme() {
return this.currentTheme;
}
}
// Usage
const themeManager = new AdvancedThemeSwitcher();
// Listen for theme changes
document.addEventListener('themechange', (e) => {
console.log('Theme changed to:', e.detail.theme);
});
6. Key Features Explained
| Feature | Description |
|---|
| FOUC Prevention | Inline script loads theme before page renders |
| localStorage | Theme preference persists across sessions |
| Smooth Transition | Fade effect when switching themes |
| Keyboard Shortcut | Ctrl+Shift+T opens theme selector |
| Responsive Design | Works on mobile and desktop |
| Custom Events | Dispatch events on theme change |
| Active Indicator | Visual feedback for current theme |
| Theme Validation | Fallback to default if theme missing |
7. Usage Tips
// Get current theme
console.log(themeSwitcher.getCurrentTheme());
// Programmatically change theme
themeSwitcher.switchTheme('darkly');
// Clear theme preference
localStorage.removeItem('adminTheme');
// Reset to default
themeSwitcher.switchTheme('bootstrap');
This solution provides:
- ✅ No FOUC with inline script
- ✅ Multiple theme options
- ✅ Smooth transitions
- ✅ localStorage persistence
- ✅ Full Bootstrap 5 admin panel
- ✅ Mobile responsive
- ✅ Clean, scalable code