← Tech-Pages

How Dark Mode Works

Dark mode isn't magic — it's just CSS variables. One line of JavaScript swaps a class on <html>, and every color in the entire page updates instantly through CSS custom properties. Click the lightbulb and watch it happen live.

💡
☀️ Light Mode Active
👆 Click to toggle!
☀️ Light
🌙 Dark
🖥️ Live Preview

Welcome to TechBlog

The best way to learn web development with interactive tutorials and real-world projects.

Get Started →
📘 CSS Flexbox
Master modern layouts with flexible boxes.
📗 JavaScript
From basics to async/await and beyond.
📕 React Hooks
Build powerful UIs with useState and useEffect.
💻 Live CSS Code
styles.css
script.js
index.html
🎨 CSS Custom Properties (Live)
🧠 How It Works
Step 1: Define Variables
In :root (the <html> element), define all your colors as CSS custom properties: --bg-color, --text-color, etc.
Step 2: Use Variables
Instead of hardcoding color: #000, write color: var(--text-color). Now every element references the variable, not a fixed value.
Step 3: Swap on Toggle
When the user toggles dark mode, JavaScript adds data-theme="dark" to <html>. A CSS rule [data-theme="dark"] overrides all variable values at once. The entire page updates instantly!
🔍 Why CSS Variables?
Analogy: The Control Panel
Imagine an entire building wired to one control panel. Instead of repainting every room, you just flip switches on the panel. CSS variables are those switches — change one, and every room (element) using it updates.
vs. Inline Styles (Bad)
Without variables, you'd need JavaScript to find and change every element individually: document.querySelector('.card').style.background = '#1e1e1e' — for EVERY element. Unmaintainable!
prefers-color-scheme
Modern browsers detect your OS setting via @media (prefers-color-scheme: dark). You can auto-match the user's system theme — no toggle needed!