HTML CSS JS

LIGHT-DARK THEME SWITCHER WITH CSS VARIABLES

<header id="head">My Site</header>   <main id="body">   THEME SWITCH BUTTONS   <p onclick="set(0)"/>Light</p>   <p onclick="set(1)">Dark</p> </main>

"USUAL" HTML LAYOUT

01

SET DEFAULT THEME :root {   --font: inherit;   --backA: inherit;   --backB: inherit; }

USE CSS VARIABLES

02

SET ELEMENTS TO USE CSS VARS #head, #body { color: var(--font); } #head { background: var(--backA); } #body { background: var(--backB); }

JAVASCRIPT THEME SWITCH (A)

03

var themes = [ LIGHT THEME COLORS {   "font": "black",   "backA": "lightblue",   "backB": "white" }, DARK THEME COLORS {   "font": "white",   "backA": "black",   "backB": "blue"  }];

SET THEME function set (t) { for (let i in themes[t]) {    document.documentElement.style.   setProperty("--"+i, themes[t][i]); }}

JAVASCRIPT THEME SWITCH (B)

04

USE LIGHT THEME AS DEFAULT set(0);