It’s the CSS property color-scheme
. This will also apply the theme on form controls, background-color and text color.
Currently supported on Chrome 81, Firefox 96 and Safari 13.
MDN source: https://developer.mozilla.org/en-US/docs/Web/CSS/color-scheme
:root {
color-scheme: dark;
}
.container {
padding: 25px;
height: 2000px;
}
<div class="container">
<div class="text">Dark Mode</div>
<input type="text" placeholder="input with dark theme"/>
</div>
If you want to change the theme on the fly, then you run into the issue where the scrollbar doesn’t update it’s color scheme until it is interacted. One way to refresh the scrollbar is to change its parent overflow property, which in this case would be the html
element.
const btn = document.querySelector("button");
let isDark = true;
btn.addEventListener("click", () => {
// remove scrollbars
document.documentElement.style.overflow = "hidden";
// trigger reflow so that overflow style is applied
document.body.clientWidth;
// change scheme
document.documentElement.setAttribute(
"data-color-scheme",
isDark ? "light" : "dark"
);
// remove overflow style, which will bring back the scrollbar with the correct scheme
document.documentElement.style.overflow = "";
isDark = !isDark;
});
[data-color-scheme="dark"] {
color-scheme: dark;
}
[data-color-scheme="light"] {
color-scheme: light;
}
.container {
padding: 25px;
height: 2000px;
}
<html lang="en" data-color-scheme="dark">
<body>
<div class="container">
<button>Click to Change Color Scheme</button>
<br>
<br>
<br>
<input type="text" placeholder="dummy input">
</div>
</body>
</html>