最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - DarkLight mode using two CSS files - Stack Overflow

programmeradmin7浏览0评论

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 and dark which the CSS uses. Then you can just switch the body class to make it independant of prefers-color-scheme. – Peter Pointer Commented Dec 29, 2021 at 8:26
Add a ment  | 

2 Answers 2

Reset to default 13

If 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)

发布评论

评论列表(0)

  1. 暂无评论