Bits Kingdom Logo

A Simple CSS Trick for Dark Mode on Your Website

The Night Mode Awaits!

by Jun 17, 2024Development

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!

Simplifying Dark Mode

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.

How It Works

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.

Why Dark Mode?

But why even bother with dark mode? Here are a few reasons:

  1. Reduces Eye Strain: Especially in low-light environments, dark mode can be easier on the eyes.
  2. Saves Battery Life: On OLED screens, dark mode can save battery life because black pixels consume less power.
  3. Looks Cool: Let’s be honest, dark mode just looks sleek and modern.

Implementing Dark Mode in Your Project

To integrate this CSS trick into your project, follow these steps:

  1. Define the Variables: Set up your CSS variables at the root level, so they can be accessed throughout your stylesheet.
  2. Apply the Media Queries: Use the prefers-color-scheme media query to adjust these variables based on the user’s preference.
  3. Style Your Elements: Use these variables in your CSS to ensure that your entire site respects the dark mode settings.

Example:

body {
  background-color: var(--body-bg);
  color: var(--body-color);
}

Conclusion: The Night Mode Awaits!

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.

Could it be interesting for you: