What is CSS variable and how to use it
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 (--).
- Declare at page level :
- Declare at element level:
- 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.
css-property: var(--yourvariablename, defaultValue);
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.
Recommended for you
No posts found
Apparently there are no posts at the moment, check again later.
No results for your search, please try with something else.
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.