CSS Variables, Dark Mode & Color Modes

Bootstrap Framework 11 min min read Updated: Nov 16, 2026 Intermediate
CSS Variables, Dark Mode & Color Modes
Intermediate Topic 5 of 10

CSS Variables in Bootstrap

Bootstrap 5 uses CSS custom properties (variables) such as --bs-primary and --bs-body-bg. You can change them with a few lines of CSS, without needing Sass.

css :root { --bs-primary: #7b2cbf; --bs-primary-rgb: 123, 44, 191; --bs-body-font-family: "Poppins", sans-serif; }

Components also have their own variables, for example a button:

css .btn-brand { --bs-btn-color: #fff; --bs-btn-bg: #7b2cbf; --bs-btn-border-color: #7b2cbf; --bs-btn-hover-bg: #5a189a; --bs-btn-hover-border-color: #5a189a; }
html <button class="btn btn-brand">Custom Button</button>

Color Modes (Dark Mode)

Since Bootstrap 5.3 you can switch between light and dark themes by adding data-bs-theme to any element.

html <html lang="en" data-bs-theme="dark">
  • data-bs-theme="dark" on <html> changes the whole page
  • Put it on a single card or navbar to make only that part dark
  • Use bg-body, text-body and bg-body-tertiary instead of fixed colors so they adapt to the theme

Dark Mode Toggle with Memory

html <button id="themeBtn" class="btn btn-outline-secondary">Toggle theme</button> <script> const root = document.documentElement; // Load the saved choice const saved = localStorage.getItem('theme'); if (saved) root.setAttribute('data-bs-theme', saved); document.getElementById('themeBtn').addEventListener('click', () => { const next = root.getAttribute('data-bs-theme') === 'dark' ? 'light' : 'dark'; root.setAttribute('data-bs-theme', next); localStorage.setItem('theme', next); }); </script>
Result

Clicking the button switches the whole page between light and dark colors. After refreshing, the page remembers your choice.

Follow the System Preference

javascript const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; document.documentElement.setAttribute('data-bs-theme', prefersDark ? 'dark' : 'light');

Tips

  • Put the theme script in the <head> to avoid a white flash before dark mode applies
  • Test images and logos in both themes
  • Avoid hard-coded colors like bg-white when you support dark mode. Use bg-body

Conclusion

CSS variables and color modes make Bootstrap customization simple. You can create a brand theme and a dark mode without compiling anything.

Quick Summary: Change --bs-* variables for branding, and set data-bs-theme to light or dark on html or any element.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators