38
loading...
This website collects cookies to deliver better user experience
class
in body
). Then you can change that property using Javascript, so that CSS variables change accordingly, affecting the child components styles as well. styles.scss
file. (In this example I am using SCSS, but it is completed optional)$bgColor_light: white;
$bgColor_dark: black;
$textColor_light: black;
$textColor_dark: white;
$borderColor_light: black;
$borderColor_dark: white;
// mixin that enables css variables in light mode
@mixin lighten() {
--bgColor: #{$bgColor_light};
--textColor: #{$textColor_light};
--borderColor: #{$borderColor_light};
}
// mixin that enables css variables in dark mode
@mixin darken() {
--bgColor: #{$bgColor_dark};
--textColor: #{$textColor_dark};
--borderColor: #{$borderColor_dark};
}
body.dark {
@include darken();
}
body.light {
@include lighten();
}
main {
display: flex;
height: 100vh;
justify-content: center;
align-items: center;
flex-direction: column;
background-color: var(--bgColor);
color: var(--textColor);
}
document.body
element programmatically./**
* Function that toggles the current mode
* Exposed publicly
*/
toggleMode() {
this.document.body.classList.toggle(Mode.LIGHT);
this.document.body.classList.toggle(Mode.DARK);
if (this.currentMode === Mode.LIGHT) {
this.updateCurrentMode(Mode.DARK);
} else {
this.updateCurrentMode(Mode.LIGHT);
}
}
@media
query@media (prefers-color-scheme: dark) {
...
}
/**
* Init function that update the application based on the initial mode value
* Flow as below
* 1 - If there is a saved mode in the browser - use this as the initial value
* 2 - If there is no saved mode, Check for the preferred device theme
* 3 - If device theme is dark, set the init value to `dark`
* 4 - Else set the default value to `light`
*/
private init() {
const deviceMode = window.matchMedia("(prefers-color-scheme: dark)");
let initMode = this.modeStorage.get();
if (!initMode) {
deviceMode.matches ? (initMode = Mode.DARK) : (initMode = Mode.LIGHT);
}
this.updateCurrentMode(initMode);
this.document.body.classList.add(this.currentMode);
}
README.md
file.