Mastodon

Automatic dark or light theme selection for Bootstrap 5

Oct 30, 2023 by Kolappan N

Dark theme support was added in bootstrap in version 5.3.0. You can set the theme for your bootstrap components at the website level by adding the data-bs-theme attribute to the html element. You can also switch between the dark and the light themes by modifying this value at any time.

Bootstrap does not switch the themes based on the OS theme as the new dark theme might not play well with your custom CSS or elements. They do provide the source code for the theme switcher in their website which has light, dark and auto mode preference.

For my use case, I just needed the auto option and here is the JavaScript I am using,

<!-- Simple script to switch bootstrap theme -->
<script>
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
        document.documentElement.setAttribute('data-bs-theme', 'dark');
        console.log('switching to dark theme');
    }

    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
        document.documentElement.setAttribute('data-bs-theme', 'light');
        console.log('switching to light theme');
    }
</script>