I am online
← Back to Articles

Implementing Light and Dark Themes with CSS

CSSMarch 20, 2024

Introduction

Learn to write CSS for both light and dark themes, and guide the browser's user agent (UA) on the default theme, while respecting user preferences.

Writing CSS for Themes

To define styles for dark and light themes, use media queries:

For dark theme:

@media screen and (prefers-color-scheme: dark) {
  p {
    color: #fff;
  }
}

For light theme:

@media screen and (prefers-color-scheme: light) {
  p {
    color: #000;
  }
}

Combining both:

p {
  color: #000;
}

@media screen and (prefers-color-scheme: dark) {
  p {
    color: #fff;
  }
}

Setting a Default Theme

As the site author, you can guide the browser on which theme to use by default.

Using a meta tag:

<meta name="color-scheme" content="dark light" />

Alternatively, use a CSS selector:

:root {
  color-scheme: light dark;
}

This sets the light theme as the default, falling back to dark if preferred by the user.

Thanks for reading, enjoy, and happy coding!