How to use CSS variables
Since I learned about CSS variables that's all I've been using for my projects. This website aside from using TailwindCSS I'm always using CSS variables as well. Let us take a look how we can accomplish that.
Per class
One way of doing this is by a class on our <html>
tag. But first, let us
write some CSS to see how it goes:
/* We can look at `:root` as when <html> has no class */
:root {
--text-color: #000;
--background-color: #000;
}
Our HTML can look something like this:
<html>
<head>
<style>
:root {
--text-color: #000;
--background-color: #000;
}
</style>
</head>
<body>
Hey there!
</body>
</html>
Let us wrap our Hey there! within a div
and apply our styling colors
to it:
<html>
<head>
<style>
:root {
--text-color: #000;
--background-color: #fff;
}
.greetings {
color: var(--text-color);
background-color: var(--background-color);
}
</style>
</head>
<body>
<div class="greetings">Hey there!</div>
</body>
</html>
Cool, our text should be #000
(dark) and our background #fff
(light).
As I've mentioned, this can be manipulated through a class
on our html
tag, let
us change that for now:
<html class="blue">
<head>
<!-- ... -->
</head>
</html>
Great, let us set our variables for when the class
is blue
shall we? Add
the following inside our <style>
tags:
[class='blue'] {
--text-color: #fff;
--background-color: blue;
}
So, we are switching our text color with #fff
and our background with blue
. If
you refresh the page is should change to our new colors.
Let us create 2 more set of colors:
[class='red'] {
--text-color: #fff;
--background-color: red;
}
[class='green'] {
--text-color: #fff;
--background-color: green;
}
Awesome! Let us create a switch for this.
The Switch
To create a switch we need to do 2 things, create a few <button>
s and
add some JavaScript code to take care of changing the class
on our
html
tag.
Buttons
Inside our <body>
tag, right after </div>
let us add a few buttons:
<button onclick="switchTheme('blue')">Blue</button>
<button onclick="switchTheme('red')">Red</button>
<button onclick="switchTheme('green')">Green</button>
So, we're creating 3 buttons with an onclick
action that will
call a function, let us create that function.
Function
Inside our <head>
that's where we'll be adding our switchTheme()
function:
<script>
function switchTheme(className) {
document.documentElement.className = className
}
</script>
Simple as that! If you try it out you should see it's applying our CSS variables.