Bootstrap Dark Mode
Bootstrap 5.3 introduced built-in support for color modes, including a dark mode, without needing extra plugins or custom CSS overrides. You enable it by setting a data attribute on the html element.
All of Bootstrap's components, colors, and utilities automatically adapt their appearance when dark mode is active, since Bootstrap's CSS variables switch values based on the color mode.
<html data-bs-theme="dark">Enabling dark mode
Add data-bs-theme="dark" to your <html> tag (or any container) to switch that section of the page into dark mode. Setting it back to "light" or removing it returns to light mode.
Toggling dark mode with JavaScript
You can let users switch themes by writing a small script that toggles the data-bs-theme attribute between 'light' and 'dark' when a button is clicked, and optionally saving the choice in localStorage.
<html lang="en" data-bs-theme="dark">
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="card">
<div class="card-body">This card automatically uses dark colors.</div>
</div>
</body>
</html>A page with a dark background and light text, including a dark-themed cardSetting data-bs-theme="dark" on the html element switches all Bootstrap components to their dark-mode colors automatically.
<button class="btn btn-secondary" onclick="document.documentElement.setAttribute('data-bs-theme', document.documentElement.getAttribute('data-bs-theme') === 'dark' ? 'light' : 'dark')">
Toggle Theme
</button>Clicking the button switches the whole page between light and dark themes instantlyThis small script flips the data-bs-theme attribute between light and dark each time the button is clicked.
Key points
- Bootstrap 5.3+ has built-in dark mode via data-bs-theme.
- Setting data-bs-theme="dark" on <html> switches the whole page's theme.
- You can scope dark mode to just part of a page by setting the attribute on a container.
- JavaScript can toggle the attribute to let users switch themes.
