CSS Variables (CSS Custom properties) for Beginners
Tags: webdev, beginners, css, javascript
Published: 2024-06-18 20:40:32

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3nvcw74sgs5oytzkwko5.jpg)


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


![image of css variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ta5ngm0plocreosz0t6q.png)

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

![Image of changing css variables with JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o167k6zpgbpobos2pjlj.png)

## 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](https://developer.mozilla.org/en-US/docs/Web/CSS)

Please check out my other articles on [Front-end development](https://dev.to/udoka033/a-beginners-guide-to-front-end-development-4hjj), [Innermost workings of the web](https://dev.to/udoka033/how-the-web-works-page-loading-and-beyond-4jd6) and [How to overcome impostor syndrome in tech ](https://dev.to/udoka033/overcoming-imposter-syndrome-as-a-beginner-in-tech-20f0).

Please like, comment and follow for more web development, and tech-related articles.