CSS detection

Documentation

In css you can use @media (prefers-color-scheme: dark) or @media (prefers-color-scheme: light)

.box {
width: 100px;
height: 100px;
}
.system-color {
background-color: white;
}
@media (prefers-color-scheme: dark) {
.system-color {
background-color: black;
}
}

Example

Also can be useful link tag

<link rel="stylesheet" href="./dark.css" media="(prefers-color-scheme: dark)">

Javascript detection

In JavaScript you can use matchMedia(docs) method

//return boolean
window.matchMedia('(prefers-color-scheme: dark)').matches

In you want to handle change use addListener(older browsers) or addEventListener(docs)

const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');

function handleSystemThemeChange(evt) {
if (evt.matches) {
console.log('dark mode');
} else {
console.log('light mode');
}
}
handleSystemThemeChange(mediaQueryList)// dark mode

// Add the callback function as a listener to the query list.
mediaQueryList.addEventListener(handleOrientationChange);

Please let me know if it can be better!

Join Telegram

--

--