Dark Mode in a single CSS theme file (dark first version)
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="dark light">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="bootstrap-unlit.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 `light
` 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: light)").matches) {
$("html").removeClass("dark").addClass('light');
} else {
$("html").addClass("dark").removeClass('light');
}
}
// Update on first load.
updateDarkColorScheme();
// and every time it changes
if (window.matchMedia) window.matchMedia("(prefers-color-scheme: light)").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.