Modern Frontend Tutorial
How to Build a Pure CSS Dark Mode Toggle (No JavaScript)
Maximize performance by leveraging the native power of the CSS :has() selector.
In 2026, web performance is the top ranking factor on Google. Heavy JavaScript theme switchers can slow down your site and cause layout shifts. At FAMOUSCODE.DEV, we believe in lightweight solutions. Today, we will use the breakthrough :has() selector to create a flicker-free Dark Mode toggle.
1. Live Interactive Demo
2. The Complete Source Code
Copy the code below to implement a production-ready dark mode on your blog or website.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pure CSS Dark Mode | FamousCode.dev</title>
<style>
body {
margin: 0;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
transition: 0.5s ease;
background-color: #ffffff;
color: #111;
font-family: 'Inter', sans-serif;
}
/* The Magic :has() Selector */
body:has(#toggle-mode:checked) {
background-color: #0f172a;
color: #f8fafc;
}
#toggle-mode {
width: 60px;
height: 30px;
cursor: pointer;
accent-color: #1a73e8;
}
</style>
</head>
<body>
<div style="text-align: center;">
<h1>Theme Switcher</h1>
<input type="checkbox" id="toggle-mode">
<label for="toggle-mode" style="display: block; margin-top: 10px; font-weight: 600;">
Switch Theme
</label>
<p>Built by FamousCode.dev</p>
</div>
</body>
</html>
🚀 Level Up Your Career
Daily viral HTML, CSS, and JS tips for modern developers.
Follow @famouscode.dev