How TO - Toggle Dark Mode


Switch between dark and light mode with CSS and JavaScript.


Try it Yourself »


Toggle Class

Step 1) Add HTML:

Use any element that should store the content you want to toggle the design for. In our example, we will use <body> for the sake of simplicity:

Example

<body>

Step 2) Add CSS:

Style the <body> element and create a .dark-mode class for toggle:

Example

body {
  padding: 25px;
  background-color: white;
  color: black;
  font-size: 25px;
}

.dark-mode {
  background-color: black;
  color: white;
}


Step 3) Add JavaScript:

Get the <body> element and toggle between the .dark-mode class:

Example

function myFunction() {
  var element = document.body;
  element.classList.toggle("dark-mode");
}
Try it Yourself »

Tip: Also see How To Add A Class.

Tip: Learn more about the classList property in our JavaScript Reference.


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.