简体   繁体   English

使用两个 CSS 文件的暗/亮模式

[英]Dark/Light mode using two CSS files

I am using a web software, that allows to create themes.我正在使用允许创建主题的 web 软件。 It creates a single CSS file per theme, so i've got two CSS files: dark.css and light.css.它为每个主题创建一个 CSS 文件,所以我有两个 CSS 文件:dark.css 和 light226EB7A628FBA26AEE2

What's the best way to create a dark/light mode switch (independent from the visitor's system settings) using both CSS files?使用 CSS 文件创建暗/亮模式切换(独立于访问者的系统设置)的最佳方法是什么? 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.如果这有助于实现平滑切换,我可以将 CSS 文件内容嵌入到 DOM 中。

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.然后浏览器将使用用户的系统配色方案来确定使用哪一组 CSS。

(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) (对于旧版浏览器,最好只让其中一个文件具有媒体查询,然后包含该文件)

If you'd like to keep CSS files separate you can use:如果您想将 CSS 文件分开,您可以使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM