How to Create a Dark Mode Toggle with CSS Variables and JavaScript

How to Create a Dark Mode Toggle with CSS Variables and JavaScript

Want to stop your site from blinding users at night?
Dark mode is no longer a gimmick, it’s expected, and adding it keeps readers engaged.
In this guide you’ll build a lightweight dark mode toggle using CSS variables (custom properties) and a few lines of JavaScript.
You’ll set color tokens in :root, override them under data-theme=”dark”, flip the attribute with a button, and persist the choice in localStorage so the site remembers the user’s next visit.
By the end you’ll have a smooth, accessible toggle that applies instantly.

Building the Core Dark Mode Toggle Functionality

jexY8FWAWQ-jIWwUM2L5Cw

Dark mode toggle with CSS variables and JavaScript needs three coordinated pieces. You’ll define color tokens as CSS custom properties inside :root, reassign those tokens under a data-theme=”dark” selector, and use var() references everywhere so switching data-theme instantly applies the new palette. The entire approach avoids page reloads and keeps styling predictable.

Next, add a simple button in your HTML. A plain

Check out our other content

Check out other tags: