Variables in CSS


CSS variables (also referred as CSS custom properties) are just like simple variables in other programming languages. They reduce the redundant work. They are used to storing values and reused at multiple places and updated/modified from one place.

Syntax:

CSS variable is any CSS property whose name starts with two dashes. Like

Custom property names are case-sensitive,  –-primary-color  and  –-Primary-Color will be treated as separate. 

Var() Function:

To use custom property value var()function is used.

The var() function retrieves and replaces itself with the custom property value, resulting in color: #212b36; As long as the custom property is defined somewhere in the stylesheet it should be available to the var function.

var()function allows two arguments, 

–custom-name: This parameter accepts the name of the custom property.

value: This is optional parameter and it accepts the fallback value.

Cascade:

Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules, can be made conditional with @media and other conditional rules, can be used in HTML’s style attribute, can be read or set using the CSSOM, etc

Benefits: 

  • CSS variables remove the redundancy in the code.
  • Cleaner Stylesheets – CSS variables make code more readable and easier to maintain.
  • Flexible – CSS Variables can be declared anywhere.
  • Access in JavaScript: CSS variables values can be easily read and written by JavaScript.
  • Easier theming: CSS variables can be used to theme and skin entire pages, components.

Browser compatibility

The browser supported by custom properties are listed below:

  • Google Chrome 49.0
  • Microsoft Edge 15.0
  • Firefox 42.0
  • Safari 9.1
  • opera 36.0

Leave A Comment

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