Dark Mode in a single CSS theme file
Basic Setup
- A single, fully themed, 2 color mode, Bootstrap CSS
- Filtered internally by stylesheet media filters
- Does not require and additional JavaScript, or jQuery
Replace the bootstrap stylesheet with the following code:
<!-- Inform the browser that this page supports both dark
and light color schemes, and the page author prefers light. -->
<meta name="color-scheme" content="light dark">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="bootstrap-dark.css">
This is all you need to enable dark mode with Bootstrap.
If you need to notify other components that the color-scheme has changed you can use this example additional code.
Advanced Features
You may also want to be notified when the browser changes the color scheme. For example you may want to toggle a `dark
` class in the `<html>` with this code:
<script>
$(document).ready(function(){
// dark mode update and listner
function updateDarkColorScheme() {
if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) {
$("html").removeClass('light').addClass("dark");
} else {
$("html").addClass('light').removeClass("dark");
}
}
// Update on first load.
updateDarkColorScheme();
// and every time it changes
if (window.matchMedia) window.matchMedia("(prefers-color-scheme: dark)").addListener( updateDarkColorScheme );
});
</script>
You really don't need the additional code. This is only usefull if you have other dependancies that have not been coded to support dark mode.