Binary theme switcher component

Web development


A lot of websites nowadays have this feature of having two color schemes for the user to choose, namely “dark” and “light”, implementing this is a peace of cake with the help of CSS custom properties (variables) and a bit of ECMAscript. Today I present you a web component that abstracts the ECMAscript part and lets you switch between the themes dynamically.

Using the component is straightforward. The component adds and updates a data attribute “data-theme” to the body element which you can handle in CSS via attribute selectors, so depending on the theme you have you can update your theme variables.

See a live demo before using it.

Usage example

To install it use your preferred package manager.

npm install theme-switcher-component


yarn add theme-switcher-component

In a .html file include and declare the component.

<html lang="en">
    <meta charset="utf-8">
    <title>Theme switcher component demo</title> 
    <link rel="stylesheet" href="./styles.css">
    <!-- Include the component -->
    <script type="module" src="./node_modules/theme-switcher-component/switch.js" defer></script>

        <p>Components are not applications, they are just a part of the whole.</p>
        <!-- Declare the component -->
        <!-- The first element of the array themes defines the default theme -->
        <theme-switcher themes='["light", "dark"]' verbose title="switch themes"></theme-switcher>


Note: other names rather than the typical “light” and “dark” can be defined for example “solarized” and “tango”.

In a .css file declare in the root selector the css variables to use and change their values accordingly to the two themes defined selecting the body.

/* Define a theme with variables */
:root {
  /* Light theme the default*/
  --border-color: black;
  --bg-color: white;

/* Change variables values accordingly*/

  --border-color: white;
  --bg-color: black;

/* ... More CSS rules below ... */

After a theme is changed, it gets stored to localStorage, if you want to see values of the local store and the current theme set the verbose attribute to the custom element, like the example.

That’s it ! Hope this helps you.

If you want more in depth documentation check the github repository and the live demo code .