How to use Variables in CSS?

In this Tutorial, I will show you how to use variables in CSS on the :root pseudo selector and show you how to access them using the var() function.

See also

Syntax of the var() Function

The var() function is used to insert the value of a CSS variable.

The syntax of the var() function is as follows:

var(--name, value)

What are CSS Vars and How to Create Custom Variables in CSS?

The var() function is used to insert the value of a CSS variable.

--css-variable-name: css property value;

Example

In this example, I want to create custom background and text color variables that I can reuse throughout the stylesheet. I am going to name these variables --bg-color and --text-color.

:root {
  --bg-color: #f6f7fb;
  --text-color: #fff;
 }

In my body selector, I am going to reference those variables using the var() function.

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}

In this second example, I have 12 numbers button on the page. I first created the HTML markup for the number buttons.

<div class="container">
      <div class="clock">
         <span style="--i:1;"><b>1</b></span>
         <span style="--i:2;"><b>2</b></span>
         <span style="--i:3;"><b>3</b></span>
         <span style="--i:4;"><b>4</b></span>
         <span style="--i:5;"><b>5</b></span>
         <span style="--i:6;"><b>6</b></span>
         <span style="--i:7;"><b>7</b></span>
         <span style="--i:8;"><b>8</b></span>
         <span style="--i:9;"><b>9</b></span>
         <span style="--i:10;"><b>10</b></span>
         <span style="--i:11;"><b>11</b></span>
         <span style="--i:12;"><b>12</b></span>
      </div>
   </div>

I then created a set of custom i variables.

.clock span{
  position: absolute;
  transform: rotate(calc(30deg * var(--i)));
  inset: 12px;
  text-align: center;
}

.clock span b{
  transform: rotate(calc(-30deg * var(--i)));
  display: inline-block;
  font-size: 24px;
  padding: 5px;
}

Conclusion

CSS variables are custom variables that you can create and reuse throughout your stylesheet.

You can always support by sharing on social media or recommending my blog to your friends and colleagues.  If you have any suggestions or problems about this tutorial, please comment on the  form below.😊

Leave a Reply

Your email address will not be published. Required fields are marked *