Using CSS variables for theming
I have restyled my site slightly, and as you might have noticed, I added a theme selector in the top right corner.
Using CSS variables, it is very easy to do and great fun too.
Basically this works by setting a “root” with your default css variables
1 2 3 4 |
:root { --background: #1B2B34; --text: #ffffff; } |
which are then used for example in the body
1 2 3 4 |
body { background: var(--background); color: var(--text) } |
When the select dropdown is changed, some JavaScript fires, adding a data attribute called “theme-slector” to the body element
1 2 3 4 5 6 7 |
const selectElement = document.getElementById("theme-selector"); selectElement.addEventListener("change", function () { const selectedValue = this.value; document.querySelector("body").setAttribute("data-theme", selectedValue); }); |
finally, we add some more CSS so that it corresponds to the chosen theme
1 2 3 4 |
body[data-theme="light"] { --background: #ffffff; --text: #000000; } |
Here is a Codepen showing it in action:
See the Pen
CSS variables for theming by Alessandro Muraro (@akmur)
on CodePen.
0