In our projects, we often encounter repetitive values such as width, color, font, etc. These values can lead to redundancy in our work and make it difficult to change on large projects.
This guide explains CSS variables also known as CSS custom properties in a beginner-friendly manner and a step-by-step guide for changing CSS values using JavaScript when a user performs an action such as a click.
By implementing CSS Variables, you can streamline your design process and improve the efficiency of your project.
Prerequisite: A basic knowledge of HTML, and CSS is required to comprehend this article.
What are CSS Variables?
You may be wondering if "variables" exist in CSS(Cascading Style Sheets) as it does in programming languages, and the answer is "yes". CSS variables also known as CSS custom properties are entities defined by CSS authors that express certain values to be reused across the components.
This means that CSS provides you with a tiny storage of value that can be referenced as many times as possible within your project.
Let's break this down,
Imagine two people working on a project that requires changing a brand color from red to green. Person1 edits the color on all elements in the project to green, while Person2 simply changes the CSS value on their variable to green and everything works just fine. Would you rather be Person1 or Person2?
Benefits of Using CSS Variables
Improves the readability and semantics of code
Makes changing repetitive values a lot easier.
Easy update of values dynamically using JavaScript, offering flexibility in response to user actions or clicks.
How to Declare CSS Variables
CSS variables can be declared using two dashes as a prefix for the CSS style property name, and any valid CSS value.
Syntax
--variable-name: value
This can be declared locally or globally depending on your specific need.
Local declaration means declaring the variable inside a CSS selector and, hence can only be accessed inside that scope.
/* this is a local declaration*/
header{
--brand-color: red
}
Global declaration is done using :root pseudo-class. This makes the variable accessible globally.
/* this is a global declaration*/
:root{
--brand-color: red
}
💡Note: CSS variable names are case-sensitive hence primary-Color and primary-color are not the same.
How to Access CSS Variables
CSS variables are accessed using the var() function.
selector{
property: var(--variableName)
}
How to Change CSS Variables Using JavaScript
This is helpful when there is a need to change some values when a user performs a particular action. For example, when a user should select fonts, colors, and themes on your website.
To change CSS values based on the user's actions, you have to take the following steps;
Step 1: Setup Your HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<script src="./app.js"></script>
<title>Document</title>
</head>
<body>
<header>
<h1>Hello There</h1>
<p>This is a paragraph</p>
<button id="button" onclick="handleClick()">Change Color here</button>
</header>
</body>
</html>
Step 2: Style your CSS;
:root{
--primary-color: blue;
}
h1{
color: var(--primary-color)
}
p{
background-color: var(--primary-color);
}
button{
border: 5px solid var(--primary-color)
}
Output
Step 3: JavaScript;
Manipulate the DOM (Document Object Model) and get the CSS selectors. e.g :root
const changeButton = document.getElementById('button')
const root = document.querySelector(':root')
Create a function for handling the click event.
In the function, change the root value by using the "setProperty" method.
function handleClick(event) {
root.style.setProperty('--primary-color', 'green')
}
The Script.js
const changeButton = document.getElementById('button')
const root = document.querySelector(':root')
function handleClick(event) {
root.style.setProperty('--primary-color', 'green')
}
Output after click
In Conclusion
This method works perfectly with any CSS value such as fonts, width, colors, etc.
To read more on CSS Style Properties please visit MDN
Please check out my other articles on Front-end development, Innermost workings of the web and How to overcome impostor syndrome in tech .
Please like, comment and follow for more web development, and tech-related articles.
Top comments (14)
CSS Variables are definitely one of my favorite new(ish) features in CSS. I don’t even want think back to when they weren’t a thing! 😂
a helpful tip for your future posts, when creating a code block with 3x ticks, if you follow the opening ticks with language you’re using you will get automatic code highlighting
so if you do this…
(without the spaces)
it will turn this…
into this…
keep up the good work! 😀
Oh Wow
Thank you so much for this @wraith
I was looking for a way to do that.
Thanks for reading.
I thought declaring variables in css was only possible through preprocessors such as scss, not knowing this.Great addition to my knowledge. THANKS!
I'm glad you learned something new.
Thanks for reading @mini2809
Well done.
Thank You @karenpayneoregon
What's the purpose of using const changeButton = document.getElementById('button') if the handleClick function is triggered directly from the HTML?
Oh, thanks for your observation. I intended to show the two ways of triggering onclick, but I mistakenly skipped it in the article.
This would definitely help in my smaller projects
Thanks for reading @sandeepkumarkuanar
Does it mean we don't need to use sass for variables in css?
CSS allows you to declare and use variables now.
However, if you have other project requirement that demands using Sass, you can then use Sass, but you don' t need to use sass for variables in CSS.
Thank you for reading @c9hp
Thank you for posting this.
I'm glad you like it @best_happy_0140a4eb45bede