Light/Dark Theme Switching
This examples uses the prefers-color-scheme
media query to switch between light and dark themes automatically.
The theme can be switched by changing your system theme if your browser supports it.
Example HTML
<link href="../dist/tower-dark-theme.min.css" rel="stylesheet" media="(prefers-color-scheme:dark)" id="default-theme" />
<link href="../dist/tower-light-theme.min.css" rel="stylesheet" media="(prefers-color-scheme:light)" />
<link href="../dist/tower-light-theme.min.css" rel="stylesheet" media="print" />
<script>
// Check if the browser doesn't support prefers-color-scheme
if (window.matchMedia('(prefers-color-scheme: dark)').media === 'not all') {
// Hide the page content until the CSS loads
document.documentElement.style.display = 'none';
// Get the href of the default theme
var cssHref = document.getElementById('default-theme').getAttribute('href');
// Add a new stylesheet link without a media attribute
document.head.insertAdjacentHTML(
'beforeend',
'<link href="' + cssHref + '" rel="stylesheet" id="fallback-theme" />'
);
// Once the fallback stylesheet is loaded show the page content
document.getElementById('fallback-theme').addEventListener('load', function (e) {
document.documentElement.style.display = '';
});
}
</script>