If you want to simplify your theme color variables, consider using a set of general color variables instead of specific ones for each theme. Define these variables in the body
element and override them as needed.
Apply the color variables to your HTML elements as usual, but change the attribute of the body
element to switch themes.
Make sure to also have contrasting color variables along with your theme colors. For example, ensure that text remains legible when switching from light to dark backgrounds.
In this example, primary and secondary theme colors are set in the body element and modified when the body has the "dark" class:
document.querySelector("button").addEventListener("click", () => document.body.classList.toggle("dark"));
body {
--color-primary: #b4e9ce;
--color-primary-contrast: #000000;
--color-secondary: #308d43;
--color-secondary-contrast: #ffffff;
/* Additional theme colors... */
}
body.dark {
--color-primary: #202d26;
--color-primary-contrast: #ffffff;
--color-secondary: #8f8f8f;
--color-secondary-contrast: #000000;
/* Additional theme colors... */
}
button {
padding: 10px;
margin-bottom: 20px;
}
.wrapper {
padding: 20px;
background-color: var(--color-primary);
border: solid var(--color-secondary) 10px;
}
.wrapper h1 {
font-family: sans-serif;
text-align: center;
color: var(--color-primary-contrast);
}
<body>
<button>Toggle Theme</button>
<div class="wrapper">
<h1>Hello World</h1>
</div>
</body>