Is there a way to toggle dark mode in Bootstrap using theme variables dynamically?
Asked on Oct 24, 2025
Answer
Yes, you can toggle dark mode in Bootstrap by dynamically changing theme variables using JavaScript. This involves switching between Bootstrap's default and dark theme CSS classes.
<!-- BEGIN COPY / PASTE -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.3.0/css/bootstrap-dark.min.css" rel="stylesheet" id="dark-theme" disabled>
<div class="container">
<button id="toggle-theme" class="btn btn-primary mt-3">Toggle Dark Mode</button>
</div>
<script>
const toggleButton = document.getElementById('toggle-theme');
const darkTheme = document.getElementById('dark-theme');
toggleButton.addEventListener('click', () => {
darkTheme.disabled = !darkTheme.disabled;
});
</script>
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with Bootstrap 5 best practices.- The example uses two Bootstrap CSS files: one for the default theme and one for the dark theme.
- The `dark-theme` link element is initially disabled to load the default theme.
- JavaScript toggles the `disabled` attribute of the `dark-theme` link to switch themes.
- Ensure both CSS files are correctly linked from a CDN or local files.
Recommended Links: