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 Why should you even use these Custom properties when You have Preprocessors? Well, Let's Answer that
Why use CSS Custom Properties over SASS variables
- Learning SASS for only using Variables is much of an effort, so why do it?
- No need for a compiler to convert your SASS files into normal CSS.
- Native, therefore fast and browser compatible.
- More CSS variables = Less JS
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. Custom properties are very helpful in large projects.
In normal CSS you have to redefine a property like colour or font repetitively for different elements and it is a hazard.
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.
Features of CSS Variables
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.
- Redefining Your Variables: An Environment is like a world within itself for a code block. The Code within an environment doesn't care anything about anything outside its environment and obeys the rules of its 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.
- Using
calc()
function with your variables: Thecalc()
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.
This blog was just an introduction to the awesomeness of CSS variables.
There are a whole lot of things you can achieve with the custom properties and with your creativity, so keep practising with them.
Until Next Time,
Happy Debugging Coding👋