[go: up one dir, main page]

DEV Community

Cover image for AWESOME CSS FEATURE ⭐
Mince
Mince

Posted on • Edited on

AWESOME CSS FEATURE ⭐

Hi, guys it's me MINCE again. If you don't follow me I am Mince a UI designer for the web. From the intro you might get it that I love CSS. Yeah, it's true. Today, we will talking about variables in CSS.

The Basics

For storing values in CSS and reusing them you can create variables. Once changed they change where ever you declared them. Just like javascript, css, python or any other programming language.

Fun fact: variables is one of the most common thing in every programming language. But, their syntax is different in every language

The syntax for variables in css is a bit complicated. But it will come handy. So, why not ? You declare all the variables in the *::root * selector. Like this:

::root{

   variables here...

}
Enter fullscreen mode Exit fullscreen mode

Then to declare a variable's name you enter the name with two "--" ( dashes ) in front of the name. Something like this.

::root{

--name: ;

}
Enter fullscreen mode Exit fullscreen mode

Now inside this "--name" you can store any css code like colours, certain animation, width, height, margin and everything. Here's an example for you


::root{

--background: black;
--box-anime: box-turn 2s infinite;
--height: 45vw;

}

Enter fullscreen mode Exit fullscreen mode

Now, does it make sense. But how do you use them. Well that's simple, just enter the name of the variable in the var() function. Like this:

element{
   background: var(--bg);
}
Enter fullscreen mode Exit fullscreen mode

That's all

But, why variables

Variables in css let you change data dynamically suppose you have a colour let's say orange. When you click a button orange should change into black. Well for this you select every element in js and then change the background colour of every element individually. This will take a ton of time. With, CSS variable you take the "--color" variable and change it. Well, that's more simple. It can also simplify your process if you have dark and light mode shifting in your application. It's useful to make responsive website simply when used along with media queries. So, give it a try

Comment, if you have any doubts.

Thanks for reading 😉..

Links 🔗:

W3schools article
My website
Daily.dev
Codepen

Top comments (3)

Collapse
 
dino2328 profile image
developer

Very good explanation.

Collapse
 
gauravchandra profile image
Gaurav Chandra

What is the difference between root and host?

Collapse
 
mince profile image
Mince

:host is used to style the orginal element while inside an element that is created while :root is the first element in all the element tree