DEV Community

arnu515
arnu515

Posted on

Auto Dark/Light Theme using CSS Only!

You no longer need theme switcher buttons, or some crazy javascript to determine what theme a user wants, because a user's computer, or browser rather, knows what theme they want!

Modern browsers like Firefox and Chrome support dark mode. Along with supporting dark mode, they also tell the website what theme is currently being used. Sites like duckduckgo use this information to automatically switch this theme based on your browser's theme, and you can get this information using CSS! Let's see how

A simple website.

I'm going to make a simple website that uses 2 colors, one for the background, and the other for text.



<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Automatic css theme switcher</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <h1>My amazing website!</h1>
    <p>It looks so good right?</p>
  </body>
</html>


Enter fullscreen mode Exit fullscreen mode

The CSS

We're going to use CSS Variables (yeah I bet you didn't know CSS had support for variables) for this. In the :root selector, we define our variables, and we can use it everywhere else. Hence, when we change these variables, the color of the website changes. We change these variables using a certain @media selector called prefers-color-theme. Let me show you the code:



/* style.css */

@import url("https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap");

:root {
  --text: #000;
  --bg: #fff;
}

body {
  font-family: "Source Sans Pro", sans-serif;
  background-color: var(--bg);
  color: var(--text);
}

@media (prefers-color-scheme: dark) {
  :root {
    --text: #fff;
    --bg: #000;
  }
}


Enter fullscreen mode Exit fullscreen mode

Hence, using the @media selector, we're changing the theme based on the users settings. Let me show you a demo:

Alt Text

Code and Playground

I wrote this code on CodeSandbox, so you can easily use the code in your projects. In fact, you can use it here!

Top comments (0)