A Comprehensive Guide to CSS Variables with Real Examples

A Comprehensive Guide to CSS Variables with Real Examples

A detailed guide on how to use CSS variables.

Introduction: 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 provides an in-depth understanding of CSS Variables and offers effective ways to use them to avoid repetitive values. 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 fully understand 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 singly edits the color on all elements in the project to green, while Person2 simply changes the value on their variable to green and everything works just fine.

Would you rather be Person1 or Person2?

This takes us to the benefits of CSS variables;

Benefits of Using CSS Variables

  • It helps improve the readability and semantics of code

  • It makes changing repetitive values a lot easier.

How to Declare CSS Variables

CSS variables can be declared using two dashes as a prefix for the property name, and any valid CSS value.

--variable-name: value

This can be declared locally or globally depending on your specific need. Local declaration means declaring the variable inside a selector, hence can only be accessed inside that scope. While global declaration is done using :root pseudo class. This makes the variable accessible globally.

/* this is a local declaration*/
header{
--brand-color: red
}
/* this is a global declaration*/
:root{
--brand-color: red
}
💡
Note: CSS variable names are case sensitive

How to Access CSS Variables

CSS variables are accessed using the var() function. This is used to insert the variables are follows.

selector{

property: var(--variable)

}

:root{
--brand-color: red;
}

header{
background-color: var(--brand-color)
}

How to Change CSS Variables Dynamically using JavaScript

This proves helpful when there is a need to change some values when a user performs a particular action. For example, when a user should be able to select fonts, themes, on your website.

So to change values based on the user's actions, you have to take the following steps;

<!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>

Your CSS;

:root{
    --primary-color: blue;
}
h1{
    color: var(--primary-color)
}
p{
    background-color: var(--primary-color);
}
button{
    border: 5px solid var(--primary-color)
}

Your JavaScript;

const changeButton = document.getElementById('button')
const root = document.querySelector(':root')

function handleClick(event) {
root.style.setProperty('--primary-color', 'green')
}

Output before click;

Output after Click;

This method works perfectly with any CSS value such as fonts, width, colors, etc.

Conclusion

We have completed CSS variables, their benefits, and how to implement them in your project. Are you going to be trying this out? Remember to Check out other features of CSS styling.