优化暗色主题集成的 SCSS 代码

问题描述

我成功地在我的网站上集成了一个深色主题,并让用户通过三个选项选择他们想要的:

  • 默认为系统(遵循操作系统界面颜色),使用 prefers-color-scheme ;
  • 浅色主题(强制使用旧的浅色主题);
  • 深色主题(无论操作系统界面如何,都强制使用新的深色主题)。

我的网站在 Ruby on Rails 上运行,并使用带有 SCSS 的资产管道。我做了以下整合暗模式:

/* darkmode.scss */
@mixin dark {
/* all the colours/css changes to make the website dark */
}

/* use the dark mode when OS interface is light */
@media (prefers-color-scheme: light) {
  [data-color-mode="dark"] {
    @include dark;
  }
}

/* Follow the OS interface colours or force the use of the dark theme */
@media (prefers-color-scheme: dark) {
  [data-color-mode="auto"],[data-color-mode="dark"] {
    @include dark;
  }
}

然后在我的应用程序视图中,我只设置了数据属性:

<html lang="en" data-color-mode="<%= (@current_user&.preferred_theme || "auto") %>">

效果很好。我受到 this answer 的启发而去做这件事。

不幸的是,它编译后会导致大量的 CSS 代码。首先,dark 代码显然被 @include 方法复制了两次。其次,对于每个选择器,[data-color-mode] 属性都会像这样重复:

[data-color-mode="auto"] ul.disclist li a,[data-color-mode="auto"] .profile_info a,[data-color-mode="auto"] .profile_user_links li a,[data-color-mode="auto"] .thumb_overlay a span,[data-color-mode="auto"] li.sotd h4 a,[data-color-mode="auto"] #online_users .footer_box a,[data-color-mode="dark"] ul.disclist li a,[data-color-mode="dark"] .profile_info a,[data-color-mode="dark"] .profile_user_links li a,[data-color-mode="dark"] .thumb_overlay a span,[data-color-mode="dark"] li.sotd h4 a,[data-color-mode="dark"] #online_users .footer_box a {
    color: #7C7C7C !important;
  }

有什么办法可以优化这一点并减少生成的代码量?我考虑过 CSS 变量,但它需要对原始设计进行全面返工。

编辑:我可以通过使用像 [data-color-mode*="a"] 这样的黑客方法来减少代码量,而不是 [data-color-mode="auto"],[data-color-mode="dark"] 但我很确定一定有更好的事情要做.这种技术导致文件删除了 400 行。

解决方法

如果您根据用户偏好使用 CSS 变量来设置颜色,它会起作用吗?

与其将 mixin 包含两次,将 css 输出量加倍,也许您可​​以只在 mixin 中设置颜色(变量),而其他样式只应用一次:

@mixin dark {
/* all the colours/css changes to make the website dark */
--text-color: #fff;
--bg-color: #000;
}

抱歉打字错误,我是用手机写的。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...