How to declare and use css variables

Posted By : Himanshu Khurana | 29-Nov-2017

CSS variables are defined by the author of the CSS that contain specific values ??to be re-used in the document. They are configured using a custom property (such as --primary-color: black;) and are accessed using the var () function, such as color: var (- primary-color);

 

Complex sites have a lot of CSS, usually with many duplicate values. For example, you can use the same color in hundreds of different places, and if the color needs to be changed, you need a global search and replace. CSS variables allow the value to be stored in one place and then referenced elsewhere. Another benefit is the semantic identifier. For example, the primary text color is easier to understand than # 00ff00, especially if the same color is used in another context.

 

Css variables is most important things. Variables declared within a CSS selector that defines its scope. For a global scope you can use the :root or body selector. The variable name must begin with two dash (--) and is case sensitive, so "--color" and "--Color" would define two different custom variables.

 

Decalares a global scope variable

:root {
  --color: #000;
}

 

To reference the variable, use the var() function. It retrieves the custom property value, so that it be assigned to the property (#000 in this case). 

#footer {
  color: var(--color);
}

 

 

I Hope this blog is helpfull for all.

Thanks

About Author

Author Image
Himanshu Khurana

Himanshu is an experienced Frontend developer with experience and capabilities to build compelling UI's for Web and Mobile Applications. Himanshu likes playing cricket and listening music.

Request for Proposal

Name is required

Comment is required

Sending message..