In this tutorial, we will explore the process of building dynamic themes for your websites using CSS Variables.
By the end of this tutorial, you will learn:
- How to define and use CSS Variables (custom properties)
- How to create flexible, switchable themes using CSS Variables
The prerequisites for this tutorial are:
- Basic knowledge of HTML and CSS
- A text editor (like Sublime Text, Visual Studio Code, Atom, etc.)
- A modern browser for testing (like Chrome, Firefox, etc.)
CSS Variables, also known as CSS Custom Properties, allow you to define reusable values. You can use them to create dynamic theming for your webpages.
You can define a CSS Variable as follows:
:root {
--main-color: #06c;
}
The :root
is a pseudo-class that selects the root element of a document. In HTML, the root element is the <html>
tag.
To use a CSS Variable, you reference it with var(--variable-name)
:
body {
background-color: var(--main-color);
}
Here's a basic example of a dynamic theme:
<html>
<head>
<style>
:root {
--main-bg-color: #f9f9f9;
--main-txt-color: #333;
}
body {
background-color: var(--main-bg-color);
color: var(--main-txt-color);
}
</style>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
We define two variables: --main-bg-color
for the background color and --main-txt-color
for the text color. We then use these variables in the body
style.
Now, let's create a switchable theme. We'll use JavaScript to switch between a light theme and a dark theme:
<html>
<head>
<style>
:root {
--main-bg-color: #f9f9f9;
--main-txt-color: #333;
}
body {
background-color: var(--main-bg-color);
color: var(--main-txt-color);
}
</style>
</head>
<body>
<button id="theme-button">Switch Theme</button>
<p>This is a paragraph.</p>
<script>
document.getElementById('theme-button').onclick = function() {
let root = document.documentElement;
if (root.style.getPropertyValue('--main-bg-color') === '#f9f9f9') {
root.style.setProperty('--main-bg-color', '#333');
root.style.setProperty('--main-txt-color', '#f9f9f9');
} else {
root.style.setProperty('--main-bg-color', '#f9f9f9');
root.style.setProperty('--main-txt-color', '#333');
}
}
</script>
</body>
</html>
When the "Switch Theme" button is clicked, the JavaScript code checks the current background color and switches the theme.
In this tutorial, we've learned how to define and use CSS Variables to create dynamic, switchable themes for our webpages.
For further learning, you can explore how to create more complex themes and how to store user theme preferences in local storage.
Create a basic theme with three variables: --main-bg-color
, --main-txt-color
, and --secondary-color
.
Extend the basic theme by adding a theme switcher. Create a light theme and a dark theme and add a button that switches between them.
Create a more complex theme with at least five variables. Add a theme switcher that switches between three different themes.