DEV Community

Cover image for CSS Variables (CSS Custom properties) for Beginners
Kasie Udoka Success
Kasie Udoka Success

Posted on • Originally published at udokakasie.hashnode.dev

CSS Variables (CSS Custom properties) for Beginners

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.

Top comments (14)

Collapse
 
wraith profile image
Jake Lundberg

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…

` ` `css
Enter fullscreen mode Exit fullscreen mode

(without the spaces)
it will turn this…

.myClass {
  —my-css-variable: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

into this…

.myClass {
  —my-css-variable: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

keep up the good work! 😀

Collapse
 
udoka033 profile image
Kasie Udoka Success

Oh Wow
Thank you so much for this @wraith
I was looking for a way to do that.

Thanks for reading.

Collapse
 
mini2809 profile image
MINI JAIN

I thought declaring variables in css was only possible through preprocessors such as scss, not knowing this.Great addition to my knowledge. THANKS!

Collapse
 
udoka033 profile image
Kasie Udoka Success

I'm glad you learned something new.

Thanks for reading @mini2809

Collapse
 
karenpayneoregon profile image
Karen Payne

Well done.

Collapse
 
udoka033 profile image
Kasie Udoka Success

Thank You @karenpayneoregon

Collapse
 
atascii profile image
Martin M

What's the purpose of using const changeButton = document.getElementById('button') if the handleClick function is triggered directly from the HTML?

Collapse
 
udoka033 profile image
Kasie Udoka Success

Oh, thanks for your observation. I intended to show the two ways of triggering onclick, but I mistakenly skipped it in the article.

Collapse
 
sandeepkumarkuanar profile image
Sandeep Kumar Kuanar

This would definitely help in my smaller projects

Collapse
 
udoka033 profile image
Kasie Udoka Success

Thanks for reading @sandeepkumarkuanar

Collapse
 
c9hp profile image
C9

Does it mean we don't need to use sass for variables in css?

Collapse
 
udoka033 profile image
Kasie Udoka Success

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

Collapse
 
best_happy_0140a4eb45bede profile image
Best Happy

Thank you for posting this.

Collapse
 
udoka033 profile image
Kasie Udoka Success

I'm glad you like it @best_happy_0140a4eb45bede