\n\n\n Explanation: We added a heading, paragraph, and a button to toggle the theme. The button has an id=\"toggle-theme\" which we’ll use in JavaScript. 🎨 Step 2: CSS Styling with Variables Create a style.css file with the following content: :root {\n --bg-color: #ffffff;\n --text-color: #000000;\n --button-bg: #e0e0e0;\n --button-text: #000000;\n}\n\nbody {\n background-color: var(--bg-color);\n color: var(--text-color);\n font-family: Arial, sans-serif;\n margin: 0;\n padding: 2rem;\n transition: background-color 0.3s, color 0.3s;\n}\n\n.container {\n max-width: 600px;\n margin: auto;\n text-align: center;\n}\n\nbutton {\n padding: 10px 20px;\n background-color: var(--button-bg);\n color: var(--button-text);\n border: none;\n cursor: pointer;\n margin-top: 20px;\n transition: background-color 0.3s, color 0.3s;\n}\n\n/* Dark Mode Variables */\nbody.dark-mode {\n --bg-color: #121212;\n --text-color: #ffffff;\n --button-bg: #333333;\n --button-text: #ffffff;\n}\n Explanation: We define default (light mode) values in :root. When the body has the class dark-mode, the variables change. We use var(--name) to apply these values throughout the site. Transitions are added for a smooth effect. βš™οΈ Step 3: JavaScript for Toggle Logic Create a script.js file with this code: const toggleButton = document.getElementById('toggle-theme');\n\ntoggleButton.addEventListener('click', () => {\n document.body.classList.toggle('dark-mode');\n});\n Explanation: We grab the toggle button by its ID. On click, we toggle the dark-mode class on the . When dark-mode is active, the CSS variable values automatically switch. πŸ’‘ Bonus Tip: Save Theme Preference (Optional) Want the site to remember user preference? Update your script.js like this: const toggleButton = document.getElementById('toggle-theme');\n\n// Load saved theme\nif (localStorage.getItem('theme') === 'dark') {\n document.body.classList.add('dark-mode');\n}\n\ntoggleButton.addEventListener('click', () => {\n document.body.classList.toggle('dark-mode');\n\n // Save preference\n if (document.body.classList.contains('dark-mode')) {\n localStorage.setItem('theme', 'dark');\n } else {\n localStorage.setItem('theme', 'light');\n }\n});\n Explanation: We check localStorage for the saved theme on page load. When toggled, we update localStorage to remember the choice. πŸ§ͺ Final Output (Preview) When you click the button, the background, text, and button colors will change based on CSS variables. The transition is smooth, and users can switch modes anytime. 🎯 Why Use CSS Variables for Dark Mode? Cleaner Code: Centralize your color settings. Easier Maintenance: Change theme colors in one place. Dynamic Switching: Use JavaScript to update the class, and variables handle the rest. βœ… Conclusion Congratulations! πŸŽ‰ You’ve successfully created a dark mode toggle using CSS variables and JavaScript. This is a scalable and modern way to offer light/dark themes on your website. πŸ“Œ Summary Table Feature Description CSS Variables Define theme colors using --variable JavaScript Toggle Add or remove dark-mode class Smooth Transition CSS transition for pleasant effect Save Preference Use localStorage to remember theme","@type":"NewsArticle","author":[{"@type":"Person","name":"Vandu","url":"https://www.pay18news.com/author/11"}],"description":"Learn how to add a dark mode toggle to your website using CSS variables and JavaScript. Step-by-step tutorial with code examples, perfect for beginners.","inLanguage":"en","dateModified":"2025-05-27T01:50:10.308Z","mainEntityOfPage":{"@type":"WebPage","@id":"https://www.pay18news.com/how-to-toggle-dark-mode-using-css-variables-simple-guide-with-code"},"url":"https://www.pay18news.com/amp/how-to-toggle-dark-mode-using-css-variables-simple-guide-with-code","datePublished":"2025-05-27T01:50:10.308Z","publisher":{"@type":"Organization","name":"Pay18News","logo":{"@type":"ImageObject","width":180,"url":"https://www.pay18news.com/apple-touch-icon.png","height":180},"@id":"https://www.pay18news.com#organization","url":"https://www.pay18news.com","sameAs":["https://x.com/vandurkt"]},"@id":"https://www.pay18news.com/how-to-toggle-dark-mode-using-css-variables-simple-guide-with-code#article","headline":"How to Toggle Dark Mode Using CSS Variables: Simple Guide with Code","articleSection":"CSS Mastery","thumbnailUrl":"https://www.pay18news.com/view/css/how-to-toggle-dark-mode-using-css-variables.jpg"}],"@context":"https://schema.org"}
Google Advertisement

How to Toggle Dark Mode Using CSS Variables: Simple Guide with Code

Google Advertisement
πŸ”₯ Read with Full Features on Our Website

Learn how to add a dark mode toggle to your website using CSS variables and JavaScript. Step-by-step tutorial with code examples, perfect for beginners.

Published on 27 May 2025
By Vandu

Add a Dark Mode Toggle Using CSS Variables (Step-by-Step Guide)

Introduction

Dark mode has become a popular design trend in modern websites and apps. It’s easy on the eyes, improves battery life on OLED screens, and gives users a choice in how they view content. In this tutorial, you'll learn how to implement a dark mode toggle using CSS variables and JavaScript, step by step.


What Are CSS Variables?

πŸ”₯ Read with Full Features on Our Website

CSS Variables (also called custom properties) let you store reusable values in your CSS. They start with -- and are usually defined inside the :root selector. For example:

:root {
  --bg-color: white;
  --text-color: black;
}
 

These can be reused like this:

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}
 

βœ… Step-by-Step: Create a Dark Mode Toggle

🧩 Step 1: HTML Setup

We’ll start with a simple HTML file that includes a toggle button.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dark Mode Toggle</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <h1>Welcome to My Website</h1>
    <p>This is a demo of dark mode using CSS variables.</p>
    <button id="toggle-theme">Toggle Dark Mode</button>
  </div>

  <script src="script.js"></script>
</body>
</html>
 

Explanation:


🎨 Step 2: CSS Styling with Variables

Create a style.css file with the following content:

:root {
  --bg-color: #ffffff;
  --text-color: #000000;
  --button-bg: #e0e0e0;
  --button-text: #000000;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 2rem;
  transition: background-color 0.3s, color 0.3s;
}

.container {
  max-width: 600px;
  margin: auto;
  text-align: center;
}

button {
  padding: 10px 20px;
  background-color: var(--button-bg);
  color: var(--button-text);
  border: none;
  cursor: pointer;
  margin-top: 20px;
  transition: background-color 0.3s, color 0.3s;
}

/* Dark Mode Variables */
body.dark-mode {
  --bg-color: #121212;
  --text-color: #ffffff;
  --button-bg: #333333;
  --button-text: #ffffff;
}
 

Explanation:


βš™οΈ Step 3: JavaScript for Toggle Logic

Google Advertisement

Create a script.js file with this code:

const toggleButton = document.getElementById('toggle-theme');

toggleButton.addEventListener('click', () => {
  document.body.classList.toggle('dark-mode');
});
 

Explanation:


πŸ’‘ Bonus Tip: Save Theme Preference (Optional)

Want the site to remember user preference? Update your script.js like this:

const toggleButton = document.getElementById('toggle-theme');

// Load saved theme
if (localStorage.getItem('theme') === 'dark') {
  document.body.classList.add('dark-mode');
}

toggleButton.addEventListener('click', () => {
  document.body.classList.toggle('dark-mode');

  // Save preference
  if (document.body.classList.contains('dark-mode')) {
    localStorage.setItem('theme', 'dark');
  } else {
    localStorage.setItem('theme', 'light');
  }
});
 

Explanation:


πŸ§ͺ Final Output (Preview)

When you click the button, the background, text, and button colors will change based on CSS variables. The transition is smooth, and users can switch modes anytime.


🎯 Why Use CSS Variables for Dark Mode?


βœ… Conclusion

Congratulations! πŸŽ‰ You’ve successfully created a dark mode toggle using CSS variables and JavaScript. This is a scalable and modern way to offer light/dark themes on your website.


πŸ“Œ Summary Table

Feature Description
CSS Variables Define theme colors using --variable
JavaScript Toggle Add or remove dark-mode class
Smooth Transition CSS transition for pleasant effect
Save Preference Use localStorage to remember theme
❀️ Like πŸ’¬ Comment πŸ”— Share
Google Advertisement
πŸ‘‰ View Full Version on Main Website β†—
Google Advertisement
πŸ‘‰ Read Full Article on Website