Dark mode is more than just a trend — it's a user-friendly feature that improves readability and reduces eye strain. The best part? Implementing dark mode can be super simple using CSS variables and a pinch of JavaScript.

Let’s build a light/dark theme toggle in under 5 minutes!


🧠 Why Use :root and CSS Variables?

Using CSS variables (also called custom properties) allows you to:

Define your color scheme in one place

Easily switch themes dynamically

Avoid repeating values across your stylesheets


⚙️ Step 1: Setup Your HTML

Dark Mode Demo
  


  
    Dark Mode in 5 Minutes
    Toggle Theme
  
  





    Enter fullscreen mode
    


    Exit fullscreen mode
    




🎨 Step 2: Create Light & Dark Themes Using :root

/* styles.css */

:root {
  --bg-color: #ffffff;
  --text-color: #1a1a1a;
  --button-bg: #e2e8f0;
  --button-text: #000000;
}

[data-theme="dark"] {
  --bg-color: #1a1a1a;
  --text-color: #f5f5f5;
  --button-bg: #2d3748;
  --button-text: #ffffff;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
  font-family: sans-serif;
  transition: all 0.3s ease;
}

button {
  padding: 10px 20px;
  margin-top: 20px;
  background-color: var(--button-bg);
  color: var(--button-text);
  border: none;
  cursor: pointer;
  border-radius: 6px;
}



    Enter fullscreen mode
    


    Exit fullscreen mode
    




💡 Step 3: Add JavaScript to Toggle Themes

// script.js

const toggleBtn = document.getElementById("toggle-theme");

toggleBtn.addEventListener("click", () => {
  const currentTheme = document.documentElement.getAttribute("data-theme");

  if (currentTheme === "dark") {
    document.documentElement.removeAttribute("data-theme");
    localStorage.setItem("theme", "light");
  } else {
    document.documentElement.setAttribute("data-theme", "dark");
    localStorage.setItem("theme", "dark");
  }
});

// Optional: Remember user’s preference
window.addEventListener("DOMContentLoaded", () => {
  const savedTheme = localStorage.getItem("theme");
  if (savedTheme === "dark") {
    document.documentElement.setAttribute("data-theme", "dark");
  }
});



    Enter fullscreen mode
    


    Exit fullscreen mode
    





  
  
  ✅ Done! Now Test It
Click the "Toggle Theme" button to switch between light and dark themes. Your site will:Animate smoothly between modesRemember the user's last preference (thanks to localStorage)Stay maintainable by using variables 🎉
  
  
  🧪 Bonus: Add More Theming Flexibility
Want to go beyond dark mode? You can add multiple themes or responsive theme changes using the same concept!
  
  
  💬 What’s Your Favorite Dark Mode Trick?
Let me know in the comments if you've built a dark mode toggle differently — or share a link to your own themed site!