Thèmes CSS

Mécanisme complet pour activer un thème clair, sombre ou personnalisé.

Plusieurs boutons

Plusieurs boutons

HTML

<button type="button" id="themeLight">Light</button>
<button type="button" id="themeDark">Dark</button>
<button type="button" id="themeCustom">Custom</button>

CSS

:root {
    --color-bg: #ffffff;
    --color-text: #111111;
}
:root[data-theme="dark"] {
    --color-bg: #111111;
    --color-text: #ffffff;
}
:root[data-theme="custom"] {
    --color-bg: #000000;
    --color-text: #ff00ff;
}

JavaScript

const btnLight = document.getElementById("themeLight");
const btnDark = document.getElementById("themeDark");
const btnCustom = document.getElementById("themeCustom");

btnLight.addEventListener("click", () => {
    document.documentElement.removeAttribute("data-theme");
});

btnDark.addEventListener("click", () => {
    document.documentElement.setAttribute("data-theme", "dark");
});

btnCustom.addEventListener("click", () => {
    document.documentElement.setAttribute("data-theme", "custom");
});
Un bouton pour 2 thèmes

Un bouton pour 2 thèmes

HTML

<button type="button" id="themeToggle">Basculer le thème</button>

CSS

:root {
    --color-bg: #ffffff;
    --color-text: #111111;
}

:root[data-theme="dark"] {
    --color-bg: #111111;
    --color-text: #ffffff;
}

JavaScript

const btnToggle = document.getElementById("themeToggle");

btnToggle.addEventListener("click", () => {
    const current = document.documentElement.getAttribute("data-theme");

    if (current === "dark") {
        document.documentElement.removeAttribute("data-theme"); // light
    } else {
        document.documentElement.setAttribute("data-theme", "dark");
    }
});