Forum Replies Created
- AuthorPosts
-
shawn-caza
ParticipantWhile Sean Kendle’s approach can work, there’s other options that are probably cleaner and less effort to implement if you don’t need to worry about older browsers. I offer a few ideas to consider below. CSS variables is the most important one.
SCSS
To simplify working in css, you might to consider using scss.
With scss instead of prefacing all dark style with .dark-mode you could nest all your dark-mode styles inside one dark mode definition. For example:
.dark-mode{ background-color: black; a{ color: white; } //any other dark styles }
User preference media queries
To improve things further, consider that the OS often allows people to specify a dark mode preference at the system level, and we now have a well-supported media query in CSS to detect that OS preference:
@media (prefers-color-scheme: dark) { //dark styles here. }
Jason Pamental has an interesting article here on using the prefers dark media query, in addition to a user toggle on the site itself, and using css variables to switch styles in a simple powerful way. There’s a demo of the concept here.
CSS Variables
If you are able to use css variables, your could just define the css once, and simply flip the variables to switch to dark mode. This is a simplified version of the css from the above demo to illustrate how to change colours for dark mode with variables:
:root { --color-dark: #3a3a3a; --color-light: #eee; --color-text: var(--color-dark); --color-background: var(--color-light); } body { background-color: var(--color-background); color: var(--color-text); transition: background-color 0.25s ease, color 0.25s ease; } .dark-mode { /* flip the light and dark variables */ --color-text: var(--color-light); --color-background: var(--color-dark); }
- AuthorPosts