How to Add Dark Mode to Any Website (CSS + React, No Library)
How to add dark mode to a website without a library To add dark mode to a website without a library, define your colors as CSS custom properties, override them under a [data-theme="dark"] selector, toggle that attribute with a few lines of JavaScript, and apply the saved theme before the page paints to avoid a flash. The pattern works in plain HTML, React, or any framework. Step 1: define colors as CSS variables :root{ --bg:#ffffff; --text:#1a1a1a } [data-theme="dark"]{ --bg:#0e1116; --text:#e8ecf3 } body{ background:var(--bg); color:var(--text) } Step 2: add the toggle On click, switch the data-theme attribute on the root element and save the choice to localStorage so it persists between visits. Step 3: prevent the white flash on load Apply the saved theme with a small inline script in the page head, before the stylesheet loads. This sets the correct theme before the first paint, which removes the flash-of-wrong-theme most implementations suffer from. Default ...