What is CSS variable and how to use it

css-variable Feb 8, 2020

What is the CSS variable?

  • CSS variable is also known as custom properties.
  • CSS variable is one kind of store in which we store value and use it later when needed.
  • You can able to declare CSS variable at the page level and at the element level.

How to use it?

  • If you declare it at page level then you can able to use it in any elements of that page.
  • If you declare it at the element level then you can able to use it in that element and its child elements.
  • You can declare the CSS variable by prefixing the variable name with (--).
Format: 
    element {
      --yourvariablename: value;
    }

Example: 
     - Declare at page level :
       :root {
         --main-color: #af02af;
       }
         
     - Declare at element level:
       .title {
         --main-color: #af02af;
       }
  • You can use the CSS variable using var().
  • var method accepts two arguments
  • the first argument is the name of the CSS variable that you want to use
  • second is default value which is optional. if you use a CSS variable that does not exist then default value applies to the element.
Format: 
      css-selector {
        css-property: var(--yourvariablename, defaultValue);     
      }

    Example: 
      .title {
        color: var(--main-color, red); 
      }

Why you should use CSS variable?

  • Let say you have a large website in which you use 'pink' color at hundred of places.
  • Now if there is any change request from the client-side to update 'pink' color with 'black' color.
  • So, In this situation, you have to change 'pink' color with 'black' color manually at each place where you used it.
  • This is a time-consuming and repeating process.
  • So, to stop repetition and to save time you should use the CSS variable.

What you can do with CSS variable?

  • you can able to override the CSS variable for a specific element.
  • you can able to change the CSS variable at runtime by using setProperty method of element's style attribute in javascript.
  • The following link contains a live example of how to use CSS variable, override CSS variable and also changing CSS variable value using javascript:
    https://www.w3schools.com/code/tryit.asp?filename=GBOZ09LDCGQ5

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.