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 variable

which are then used for example in the body

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

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

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.

See the Pen CSS variables for theming by Alessandro Muraro (@akmur) on CodePen.

Leave a Reply

Your email address will not be published. Required fields are marked *