惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog
The Cloudflare Blog
J
Java Code Geeks
Apple Machine Learning Research
Apple Machine Learning Research
T
Tailwind CSS Blog
L
LangChain Blog
Recent Announcements
Recent Announcements
Hugging Face - Blog
Hugging Face - Blog
Microsoft Security Blog
Microsoft Security Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
V
V2EX
I
InfoQ
博客园 - 司徒正美
T
The Blog of Author Tim Ferriss
G
Google Developers Blog
云风的 BLOG
云风的 BLOG
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
H
Help Net Security
博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
B
Blog RSS Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
The Easiest Way to Add Dark Mode to Your Website
Ali Karbasi · 2026-05-27 · via DEV Community
  • Posted on Jul 28, 2024
  • 3 min read

🤖 AI summary: This tutorial outlines a method for implementing dark mode on a website using HTML, CSS variables, and JavaScript. The process involves creating a basic HTML structure with a toggle button, defining specific color variables for both light and dark themes in CSS, and using JavaScript to switch the \"dark-mode\" class while saving the user's preference in local storage. By following these steps, developers can ensure a seamless transition between themes that persists across page reloads, ultimately improving user experience by reducing eye strain and conserving battery life.

The ability to use websites and applications in dark mode has grown in popularity in recent years. It relieves eye strain, prolongs battery life on OLED-screening devices, and offers an aesthetically pleasing substitute for the traditional light theme. This tutorial will show you how to use JavaScript to toggle themes and CSS variables to add dark mode to your website.

Step 1: Setting Up Your HTML

First, let's start with a basic HTML structure. Create an index.html file with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dark Mode Example</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <header>
        <h1>Welcome to Dark Mode Tutorial</h1>
        <button id="theme-toggle">Toggle Dark Mode</button>
    </header>
    <main>
        <p>This is a sample website to demonstrate dark mode implementation.</p>
    </main>
    <script src="script.js"></script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

This HTML file includes a header with a title and a button to toggle dark mode, a main content area with some text, and links to our CSS and JavaScript files.

Step 2: Defining CSS Variables

Now let's define the variables in our CSS. Make a styles.css file with the following content:

:root {
    --background-color: #ffffff;
    --text-color: #000000;
    --header-background-color: #f1f1f1;
}

body {
    background-color: var(--background-color);
    color: var(--text-color);
    font-family: Arial, sans-serif;
    transition: background-color 0.3s, color 0.3s;
}

header {
    background-color: var(--header-background-color);
    padding: 20px;
    text-align: center;
}

button {
    padding: 10px 20px;
    margin-top: 20px;
    cursor: pointer;
}

.dark-mode {
    --background-color: #181818;
    --text-color: #ffffff;
    --header-background-color: #242424;
}

Enter fullscreen mode Exit fullscreen mode

We use :root to define a group of CSS variables in this CSS file. For the light mode, these variables determine the background color, text color, and header background color. Additionally, a .dark-mode class is defined, and its settings take precedence over these variables. A seamless transition between themes is guaranteed by the body element's transition property.

Step 3: Adding JavaScript for Theme Toggling

Now, let's add the JavaScript to handle the theme toggling. Create a script.js file with the following content:

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

// Check for saved user preference
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
    body.classList.add(savedTheme);
}

// Toggle dark mode
themeToggle.addEventListener('click', () => {
    body.classList.toggle('dark-mode');

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

Enter fullscreen mode Exit fullscreen mode

This script selects the theme toggle button and the body element. When the button is clicked, it toggles the dark-mode class on the body. The script also saves the user's theme preference in localStorage, so the theme persists across page reloads.

Step 4: Testing the Implementation

Launch your web browser and open the index.html file to test the implementation. To switch between bright and dark themes, click the "Toggle Dark Mode" button. Remember that refreshing the page shouldn't affect the theme preference.

Conclusion

You can quickly add a dark mode toggle to your website by utilizing CSS variables and a little JavaScript. This methodology facilitates seamless theme transitions and offers an enhanced user experience. Please feel free to add more elements to your page and modify the styles in order to build upon this lesson.

Happy coding :D