When incorporating a light/dark mode feature into your entire app, it's important to place the button and class condition around where your is located. The theme style should be defined in the style.css/style.scss file at the root of your app so that it can be accessed universally.
If you're not utilizing material themes, you'll need to define all variables yourself. Avoid hardcoding styles like this:
.bgnight{
background-color: #000;
color: #fff;
}
Instead, prefer using CSS variables within the :root selector to make them accessible throughout the app:
:root {
.night {
--background-color: #000;
--text-color: #fff;
}
.light {
--background-color: #fff;
--text-color: #000;
}
}
These theme variables can then be used to customize styles in the root and on other pages. All color-related properties should be defined as variables.
background-color: var(--background-color);
color: var(--text-color);
To enable users to switch between dark and light modes, you can set up a class condition like this:
It's worth noting that using a toggle button for dark mode may reset the color settings upon page refresh or app reentry. To prevent this inconvenience, ensure that the chosen mode is cached for a seamless user experience.
In handling dark and light themes, CSS media queries such as
@media (prefers-color-scheme: light)
or
@media (prefers-color-scheme: dark)
are commonly employed. These queries ascertain the user's preferred theme based on their browser settings, eliminating the need for a toggle button. You can observe this functionality on the Google website
https://www.google.com