How to Implement Dark Mode with CSS: A Simple Tutorial

Dark mode reduces eye strain and saves battery on OLED screens. With modern CSS, you can easily add dark mode support using custom properties and the prefers-color-scheme media query. This tutorial walks you through the process step by step.

The core idea is to define color variables in :root for a light theme, then automatically override them inside a media query that detects the user’s system preference for dark mode. This requires no JavaScript for the basic auto-switching behavior.

Article illustration

1. Define CSS Custom Properties for Colors

Start by declaring your theme colors as CSS custom properties in the :root pseudo-class. Use descriptive variable names like --bg and --text so you can reuse them throughout your stylesheet.

  • :root { --bg: #ffffff; --text: #000000; }
  • Add more variables as needed (e.g., --accent, --border).

2. Add the Dark Mode Media Query

Create a media query for prefers-color-scheme: dark. Inside it, reassign the same variables with darker colors. This overrides the variables when the user’s OS is set to dark mode.

  • @media (prefers-color-scheme: dark) { :root { --bg: #121212; --text: #e0e0e0; } }
  • You can also add a light query for explicit control.

3. Apply the Variables to Your Elements

Use var(--bg) and var(--text) for background and text colors on your body and other elements. Your site will now automatically switch themes based on the user’s system setting.

  • body { background-color: var(--bg); color: var(--text); }
  • Extend to other elements like cards, buttons, etc.

That’s it! With just a handful of CSS rules, you’ve implemented a clean, accessible dark mode. For a manual toggle, add a small JavaScript snippet to toggle a class – but for most sites, the auto approach is the best starting point.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *