Small Business
Web Wise: How Do I Get Technical with My Website?Chapter 4: Exploring CMS Options, Content Types, and Metrics
June 17, 2024The Night Mode Awaits!
June 17, 2024
By: Enrique
Picture this: It’s late at night, the moon is high, and you’re comfortably browsing your favorite site when—BAM!—the bright white background hits you like a spotlight. Not ideal, right?
Developers often turn this simple problem into a tech labyrinth, adding tons of classes, styles, and JavaScript files. But, dear reader, there’s a far easier way to achieve dark mode with less than 20 lines of CSS magic. Yes, you heard that right—20 lines!
By leveraging CSS, you can allow your website to seamlessly adapt to your users’ preferred theme. How? By tweaking --body-bg
and --body-color
CSS variables using media queries. In light mode, we’ll set the background to white and in dark mode, black. Here’s how:
@media (prefers-color-scheme: dark) {
:root {
--body-bg: black;
--body-color: white;
}
}
@media (prefers-color-scheme: light) {
:root {
--body-bg: white;
--body-color: black;
}
}
VoilĂ ! Now your site can transition from day to night as smoothly as a jazz musician switching keys.
The key to this magic is the prefers-color-scheme
media query. This media query checks the user’s system preference and applies the corresponding styles. When the user prefers a dark theme, the CSS variables --body-bg
and --body-color
are set to black and white, respectively. Conversely, if the user prefers a light theme, these variables are set to white and black.
But why even bother with dark mode? Here are a few reasons:
To integrate this CSS trick into your project, follow these steps:
prefers-color-scheme
media query to adjust these variables based on the user’s preference.Example:
body {
background-color: var(--body-bg);
color: var(--body-color);
}
And there you have it! A quick and fun guide to making your web development life a bit easier. If only everything in tech could be this simple, right? Now go forth and code without fear of blinding your users or getting tangled in arrays! Whether you’re a night owl coding in the wee hours or just someone who loves a sleek, modern look, this simple CSS trick has got you covered.