DEV Community

Himanshupal0001
Himanshupal0001

Posted on

So what is :root and var() in css???

Hi there, Today I will tell you what is :root and var() in css. For beginners this might be confusing most of the time when they follow long on youtube to design something. Let's talk about variables first in css. What happened? Never heard about it, well now you know there are variables in css also.

I suppose you have little knowledge on variables and their scope. There are two type of scope for variables. Global and local. Please read my js 1st day post that might clear your query on scope.
Ok, Now we know there are variables in css and there are scope for these variables. But when we gonna talk about the main topic?? I am reaching there almost '__' .

So basically - :root is used to define variables in global scope.
Why global scope? SO that we can use those variables anywhere in the css. Why not I give you an example. Suppose you want to use sexy af color in your design. But you are struggling to remember their hexa codes like #53EF44 or rgba(445,75,544) something like that and writing this again and again throughout the code is pain in the arse. In this kind of situations variables will come to rescue.I'll show you a code snippet.

:root  //global scope
{
--blue: #6495ed  //variable
--white: #faf0e6
}

body {background-color: var(--blue);} //how to use variable via var() function.
Enter fullscreen mode Exit fullscreen mode

Image description

I know what you gonna ask now. What the heck is** --blue or --white*.
So my friends these are non other then *
variable itself** and we use var() function to use these variables.

Image description

Top comments (0)