How do I swap images or logos when switching themes (light/dark)?
Asked on Jul 31, 2025
1 Answer
To swap images or logos when switching between light and dark themes in Bootstrap 5, you can use JavaScript to dynamically change the `src` attribute of an image element based on the theme.
<!-- BEGIN COPY / PASTE -->
<img id="theme-logo" src="logo-light.png" alt="Logo" class="img-fluid">
<script>
const logo = document.getElementById('theme-logo');
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
function updateLogo() {
if (prefersDarkScheme.matches) {
logo.src = "logo-dark.png";
} else {
logo.src = "logo-light.png";
}
}
// Initial check
updateLogo();
// Listen for changes in the theme
prefersDarkScheme.addEventListener('change', updateLogo);
</script>
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with Bootstrap 5 best practices.- This example uses the `prefers-color-scheme` media query to detect the user's theme preference.
- The `updateLogo` function changes the image source based on the theme.
- The `addEventListener` method listens for changes in the theme preference and updates the logo accordingly.
- Ensure that the image paths (`logo-light.png` and `logo-dark.png`) are correct and accessible.