I was able to successfully integrate a dark theme on my website and let users pick what they want with three options:
- Default to System (follow the OS interface colours), with the use of
prefers-color-scheme
; - Light Theme (force the use of the old light theme) ;
- Dark Theme (force the use of the new dark theme no matter what the OS interface looks like).
My website is running on Ruby on Rails and use the Assets Pipeline with SCSS. I did the following to integrate the dark mode:
/* 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;
}
}
Then in my application view I just set the data-attribute:
<html lang="en" data-color-mode="<%= (@current_user&.preferred_theme || "auto") %>">
It works very well. I got inspired by this answer to do it.
Unfortunately, it leads to a LOT of CSS codes after being compiled. First, the dark
code is obviously being duplicated twice with the @include
method. Secondly, the [data-color-mode]
attribute gets duplicated for every selector like this:
[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;
}
Is there any way to optimize this and reduce the amount of code generated? I thought about CSS variables but it would need a whole rework of the original design.
Edit: I was able to reduce the amount of code by using hackish methods like [data-color-mode*="a"]
instead [data-color-mode="auto"], [data-color-mode="dark"]
but I'm pretty sure there must be something better to do. This technique lead to a file with 400 lines removed.