How to Add Dark Mode to Any Website (CSS + React, No Library)

 

How to Add Dark Mode to Any Website | DesignToCodes

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 to the user's system setting with prefers-color-scheme.

Accessibility tips for dark mode

  • Keep contrast at 4.5:1 or higher in both themes
  • Give the toggle an aria-label
  • Add color-scheme: light dark so form controls adapt

Frequently asked questions

How do you add dark mode without a library?

Define colors as CSS custom properties, override them under a data-theme selector, and toggle that attribute with about fifteen lines of JavaScript. No framework or library is required.

How do I stop the white flash when the page loads?

Apply the saved theme with a small inline script in the head before your stylesheet loads, so the correct theme is set before the first paint.

Want theming done right out of the box? Browse DesignToCodes templates with a clean, variable-based dark mode built in.

Explore DesignToCodes templates →

Comments

Popular posts from this blog

Home Remodeling Website Template

Psychic Therapist Elementor Template

Interior Design Framer Template