Most dark-mode tutorials reach for a library or a theme provider. You don't need one. CSS variables already do the whole job: define your colours once, swap the values when a toggle flips, and let every element follow.
Here is the complete theme from a working demo page I built:
:root { --bg : #ffffff ; --text : #16202e ; --card : #eef2f7 ; --accent : #c9a227 ; } body .dark { --bg : #0b1220 ; --text : #f5f0e1 ; --card : #16223a ; --accent : #e7c34a ; }
Enter fullscreen mode
Exit fullscreen mode
That's the theme itself. Everything else on the page just uses the variables:
body { background : var ( --bg ); color : var ( --text ); transition : background .3s , color .3s ; } .card { background : var ( --card ); } button { background : var ( --accent ); }
Enter fullscreen mode
Exit fullscreen mode
The toggle
One button, one class on <body> , and localStorage so the visitor's choice survives the next visit:
const b = document . body ; if ( localStorage . getItem ( ' demo-theme ' ) === ' dark ' ) b .β¦