CSS Variables (CSS Custom properties) for Beginners

Kasie Udoka Success - Jun 18 - - Dev Community

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.

Image of HTML code

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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Global declaration is done using :root pseudo-class. This makes the variable accessible globally.

/* this is a global declaration*/
:root{
--brand-color: red
}
Enter fullscreen mode Exit fullscreen mode

💡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)

}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

Output

image of css variables

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')
Enter fullscreen mode Exit fullscreen mode

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')
}
Enter fullscreen mode Exit fullscreen mode

The Script.js

const changeButton = document.getElementById('button')
const root = document.querySelector(':root')
function handleClick(event) {
root.style.setProperty('--primary-color', 'green')
}
Enter fullscreen mode Exit fullscreen mode

Output after click

Image of changing css variables with JavaScript

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.

. . . . . .
Terabox Video Player