You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
To implement auto color scheme and toggle. The app starts using the color scheme of the user's operating system. The user can toggle between light and dark modes using a button, or go back to the system default.
57
+
58
+
To support this, we use a cookie to store the user's preference, the cookie is typed to have three possible values: `light`, `dark`, and `system`.
59
+
60
+
If the cookie is not set, or if the value is `system`, we use the `prefers-color-scheme` media query to determine the color scheme. If the value is `light` or `dark`, we use that value instead.
61
+
62
+
To support this, we override the `dark:` variant on the Tailwind configuration to work with both `.dark` class or `.system` class + media query.
63
+
64
+
```scss
65
+
@custom-variant dark {
66
+
/* This supports the .dark class */
67
+
&:where(.dark*, .dark) {
68
+
@slot;
69
+
}
70
+
71
+
/* This supports the .system class + media query */
72
+
&:where(.system*, .system) {
73
+
@media (prefers-color-scheme: dark) {
74
+
@slot;
75
+
}
76
+
}
77
+
}
78
+
```
79
+
80
+
This approach doesn't use any JavaScript to determine the color scheme, and doesn't have a flash of uncorrect color scheme on page load because we can read the cookie value on the server side and set the initial class on the HTML element.
81
+
82
+
And since for the `.system` class we use the `prefers-color-scheme` media query in CSS, the browser will automatically render the correct colors when the page loads, instead of needing to inject an inline script in the `<head>` to read the `window.matchMedia` value and set the class on the HTML element.
0 commit comments