undefined
undefined
It is very easy to style your application for dark-mode using BridgeCSS.
For dark mode there are often two considerations:
What is the user-preferred theme set to by default (if any)
Is there a way to manually set the theme in the user interface
With BridgeCSS these are both achieved via single mixin dark
. With the dark
mixin it will first check to see if the user has set a default color mode set, then it will look for the data-theme
attribute. If it finds data-theme="dark"
it will render the dark mode styles regardless of the set preference in the browser.
To see it in action consider the following styles:
p {
color: $gray-800;
@include dark {
// dark mode overrides go here
color: $gray-200;
}
}
So the procedure is to build your app, light-mode first and then apply the dark
mixin wherever you want to change a given style, or set of styles, in dark mode.
Toggling Dark Mode in Javascript
It may be desired to provide the user a toggle for dark-mode rather than relying only on the system preference (eg. as on this website). For a web-application the easiest way to do that is to store / reference the users’s preference from localStorage, although you could do it via database storage or in a cookie.
Dark mode will be respected in Bridge if the data-theme="dark"
property is set on the root document element. There are two steps to getting dark mode working properly. The first is getting the user’s preferred scheme, and the second is handling a manual theme selection.
For getting the user’s theme we can run a hook on mount.
let mode;
onMount(() => {
if (
localStorage.theme === 'dark' ||
(!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)
) {
mode = 'dark';
} else {
mode = 'light';
}
});
Here we are getting the user setting, and using it to set the mode
variable. The mode
variable can be used to eg. toggle between a sun and a moon icon in the user interface. Then when the user toggles the theme we run a handler:
const handleToggleDark = () => {
if (localStorage.theme === 'dark') {
localStorage.theme = 'light';
document.documentElement.setAttribute('data-theme', 'light');
mode = 'light';
} else {
localStorage.theme = 'dark';
document.documentElement.setAttribute('data-theme', 'dark');
mode = 'dark';
}
};
you may need to slightly adapt this to your javascript framework. Eg. in React you probably would want to keep the mode
as state. What we are doing here is setting the data-theme
property on the root document element. Then our mixin dark()
will respond to that value preferrentially over the user’s default theme.
Compared with utility-first
In the utility-first approach you must supply the dark:
prefix on every dark mode style that is used in a given className. This can lead to exteremly long lists of classNames in more complex cases. Whereas in the BridgeCSS approach you just need to declare every dark mode style under the same dark
mixin, reducing duplication and improving readability.