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



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

  • 默认为System(遵循OS界面颜色),使用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;
}
}

然后在我的应用程序视图中设置data-attribute:

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

效果很好。我受到这个答案的启发而去做这件事。

不幸的是,它导致编译后大量的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;
}

很抱歉,我是用手机写的。

最新更新