Simple Color Theme Switcher Implementation With CSS and Alpine.js

Dixie Atay
The Startup
Published in
5 min readAug 24, 2020
Photo by Kelli Tungay on Unsplash

As we start building a website, at some point we would wonder what will we use as our color theme. In demo sites, they usually provide such feature where user can toggle different color schemes and let them decide what they prefer. Thence, this post, is another attempt on implementing such feature.

Prepare our Web Layout

So, to start, open up your terminal and let’s create a new folder with our main html file and our assets folders.

mkdir theming && cd theming && touch index.html && mkdir -p assets/{css,js}

In the index.html file let’s add a very simple html content for our layout.

<html>
<head>
<title>Theming</title>
</head>
<body>
<div class="header">
<h1>My Simple Theme</h1>
</div>

<div class="topnav">
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
</div>

<div class="row">
<div class="column">
<h2>Column</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique. Quisque vehicula, risus eget aliquam placerat, purus leo tincidunt eros, eget luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.</p>
</div>

<div class="column">
<h2>Column</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique. Quisque vehicula, risus eget aliquam placerat, purus leo tincidunt eros, eget luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.</p>
</div>

<div class="column">
<h2>Column</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sit amet pretium urna. Vivamus venenatis velit nec neque ultricies, eget elementum magna tristique. Quisque vehicula, risus eget aliquam placerat, purus leo tincidunt eros, eget luctus quam orci in velit. Praesent scelerisque tortor sed accumsan convallis.</p>
</div>
</div></body>
</html>

Then, in your terminal, let’s add our css resource — touch assets/css/theme.css and then add the following css content to style our simple html layout.

/* Style the header */
* {
box-sizing: border-box;
}
.header {
padding: 20px;
text-align: center;
}
/* Style the top navigation bar */
.topnav {
overflow: hidden;
background-color: #333;
}
/* Style the topnav links */
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* Change color on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
/* Create three equal columns that floats next to each other */
.column {
float: left;
width: 33.33%;
padding: 15px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}

in our html, we need to update the html head part to include the newly created css file —

<head>
<title>Theming</title>
<link rel="stylesheet" href="./assets/css/theme.css">
</head>

At this point, you would have this simple and bare layout —

Let’s Start Theming!

Alpine.js in Action

Cool kids nowadays, have been using a jQuery alternative, that is alpine.js. And since, I’d like us to be one of those kids, therefore, let’s use it!

<body>        
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer></script>
<script src="assets/js/theme.js"></script>
...
</body>

Notice that we have also included assets/js/theme.js . We’ll be using it for our own Javascript needs. But before we can use it, you’ll need to create the js file first — touch assets/js/theme.js and have it with the following js content.

function theme() {
return {
colorThemes: [
'light-yellow', //#f7e8a4
'dark-blue', // #172A3A
'almond', // #d9c5b2
'green', // #04A777
],
themeClass: {},
choiceClass(className) {
const classes = {'color-choice': true};
classes[className] = true;
return classes;
},
changeTheme(className) {
this.themeClass = this.colorThemes.reduce((allClasses, cn) => {
allClasses[cn] = className === cn;
return allClasses;
}, {});
}
}
}

So what the js file does is that, it will be used to feed data to our DOM with the help of alpine.js. Awesome, right! Anyway, as you can see, we only need two properties and two functions to make our feature works —

colorThemes — our default color themes which can easily be updated anytime you want.

themeClass — will represent the class or color theme to be applied to our layout.

choiceClass() — set the color choice classes

changeTheme() — updates the class or color theme base on the selected color.

For us to utilize the preceding properties and functions, let’s now update our html.

  • We need to feed our data to a certain scope, let’s add it right in our html body and also apply the color theme class within the body element —
<body x-data="theme()" :class="themeClass">
...
</body>

themeClass is a reactive property and will be changed when it is updated via some events.

  • And for the most important part let’s add the color choices in our html. Let’s add them in our header using alpine.js. We can dynamically show our color themes this way —
<div class="header">
<h1>My Simple Theme</h1>
<div>
<span class="color-theme-container">
<template x-for="(ct, index) in colorThemes" :key="index">
<span x-bind:class="choiceClass(ct)" @click="changeTheme(ct)"></span>
</template>
</span>
</div>
</div>

There , we loop colorThemes property and add a color choice or option. We then also bind a click event for each choice so that when a choice was clicked it would update the property themeClass which eventually changes our color theme.

By now, we already have a working manipulation of color themes to our html body. However, we need to determine our css for our color themes to finally complete our color theme switcher feature.

The Power of CSS Variables

There is a great power with css variables. It makes styling more flexible and we will be utilizing it right here. In our assets/css/theme.css add the following styling —

/* Color Themes */
.light-yellow {
--background-color: #f7e8a4;
--font-color: #000000;
}
.dark-blue {
--background-color: #172A3A;
--font-color: #eee;
}
.almond {
--background-color: #d9c5b2;
--font-color: #000000;
}
.green {
--background-color: #04A777;
--font-color: #f5efef;
}
/* Color Choice */
.color-choice {
height: 30px;
width: 30px;
background-color: var(--background-color);
border-radius: 50%;
display: inline-block;
cursor: pointer;
}
.color-choice:hover {
opacity: 0.5;
}
.color-theme-container {
background-color: white;
border: 2px solid #1f1e1e;
padding: 25px 10px 5px;
}
/* Color Theme Application*/
body {
background-color: var(--background-color);
color: var(--font-color);
}

In the css, we make use of two main css variables --background-color and --font-color to every color class we have set. These variables can then be used on other css definitions which is very convenient for our color theme styling. When a certain color class is added in our html body, consequently, the variables value set for that color class will be applied to the body’s background-color and color . Nice!

And now you’ll have a simple color theme switcher like this.

I know, there are some sophisticated implementation from famous css frameworks out there, but my take on this, is to give you an idea on adding something like this in your existing project or on your simple app. Anyway, it’s been fun! I hope you enjoyed it too.

You can find the entire codes at https://github.com/dxc04/simple-theme-with-css-alpinejs .

--

--