I am using a web software, that allows to create themes. It creates a single CSS file per theme, so i've got two CSS files: dark.css and light.css.
What's the best way to create a dark/light mode switch (independent from the visitor's system settings) using both CSS files? I've tried loading the opposite theme upon click, but that's very impractical and requires at least one more roundtrip.
I can embed the CSS files contents into the DOM, if that helps to achieve a smooth switch.
I am using a web software, that allows to create themes. It creates a single CSS file per theme, so i've got two CSS files: dark.css and light.css.
What's the best way to create a dark/light mode switch (independent from the visitor's system settings) using both CSS files? I've tried loading the opposite theme upon click, but that's very impractical and requires at least one more roundtrip.
I can embed the CSS files contents into the DOM, if that helps to achieve a smooth switch.
Share Improve this question edited Apr 28, 2020 at 12:37 Sgl asked Apr 28, 2020 at 11:42 SglSgl 1251 silver badge12 bronze badges 1-
Loading both files at once is of no concern unless you have 1990s internet speed available. Loading and unloading the correct CSS file will make more problems than it solves. Alternate solution: Add a class to the body like
light
anddark
which the CSS uses. Then you can just switch the body class to make it independant ofprefers-color-scheme
. – Peter Pointer Commented Dec 29, 2021 at 8:26
2 Answers
Reset to default 13If you'd like to keep CSS files separate you can use:
<link rel="stylesheet"
href="css/light.css">
<link rel="stylesheet" media="(prefers-color-scheme: dark)"
href="css/dark.css">
The most simple solution I can think of is to just include both files and use media queries:
@media (prefers-color-scheme: light) {
/* CSS here */
}
@media (prefers-color-scheme: dark) {
/* CSS here */
}
The browser will then use the user's system colour scheme to determine which set of CSS to use.
(For the sake of legacy browsers, it's probably best to only have one of the files have the media query and include that file second)