CSS··7 min read

Dark Mode with CSS — prefers-color-scheme & CSS Variables

Implement dark mode using CSS prefers-color-scheme, data attributes, and custom properties without JavaScript flash.

dark mode CSScss dark themeprefers-color-scheme

Implementing Dark Mode in CSS

Users expect dark mode. CSS can respect system preference automatically or toggle via a class on html.

Why dark mode CSS Matters

Dark mode reduces eye strain and is a user expectation on developer tools and content sites — implement it with CSS, not heavy JS.

Combine prefers-color-scheme for auto mode with a data-theme toggle that swaps CSS variable values on the root element.

dark mode CSS — Key Ideas You Must Know

  • @media (prefers-color-scheme: dark)
  • CSS variables for theme colors
  • data-theme attribute toggle
  • color-scheme meta for native controls
  • Avoid flash with inline script or SSR

dark mode CSS Code Example

CSS
@media (prefers-color-scheme: dark) {
  :root {
    --bg: #111;
    --text: #eee;
  }
}

Practice dark mode CSS with Free Lessons

Add dark mode to a practice page after CSS variables lesson on Sturdee.

Tip: Free interactive lesson: /tutorials/css — practice dark mode CSS with runnable code on Sturdee.

Dark Mode with CSS — FAQ

Frequently Asked Questions

Dark mode and SEO?+

No direct impact. Improves UX and time-on-site indirectly.

Continue learning interactively

Free tutorial: /tutorials/css