DEV Community

Cover image for Getting started with CSS Custom Properties
Aditya Khare
Aditya Khare

Posted on • Updated on

Getting started with CSS Custom Properties

Do you know that you can use Variables in Vanilla CSS without any preprocessors like SASS or LESS
Let's Find out How...

But first the question arises that Why should you even use these Custom properties when You have Preprocessors.

Why use CSS Custom Properties over SASS variables

  1. Learning SASS for only using Variables is much of an effort, so why do it.

  2. No need for a compiler to convert your SASS files into normal CSS.

  3. Native, therefore fast and browser compatible.

Now, let's understand What the heck are these CSS Custom Properties.

What are Custom Properties

If you ever used a Programming language before, you know what a variable is.
If not, A variable is something that is defined once, usually at the top of the code, and then can be referenced later anywhere in the code.

So Basically, the custom properties are the variables of CSS which minimizes code repetition and saves time. The custom properties are very helpful in large projects.

In normal CSS you have to redefine a property like color or font repetitively for different elements and it is a hazard.

Code Snippet

Well not anymore,
Define once, use anywhere from now on.
A custom property is written with a preceding -- sign before its name with no spaces and called(used) with the var() keyword.

Code Snippet

Features of CSS Variables

  1. Flexibility: One great benefit of Custom properties is that you can structure and combine different variables for more flexibility. Any value you can think of can be converted into a variable.

Code Snippet

  1. Redefining Your Variables: An Environment is like a world within itself for a code block. The Code within a environment doesn't care anything about anything outside it's environment and obeys the rules of it's own Environment.

With CSS variables, You can also redefine or change the value of a custom property with a new value within a specific element and it will work with that value in its local environment instead of the globally defined custom property.

Code Snippet

  1. Using calc() function with your variables: The calc() function can perform basic mathematical operations in CSS. Make your whole layout responsive by using it with predefined custom properties which helps in structuring the sizes of your elements. Code Snippet

You can do so much more with custom properties.
Comment how you utilize and make the best use of CSS custom properties.
This post is a result of my Twitter Thread on the Custom Properties, if you like to see more follow me on my twitter handle.

Top comments (0)