What is the difference between CSS variables and preprocessor variables ?
Variables are one of the major reasons CSS preprocessors exist at all. The ability to set a variable for something like a color, use that variable throughout the CSS you write, and know that it will be consistent, DRY, and easy to change is useful. You can use native CSS variables ("CSS Custom Properties") for the same reasons. But there are also some important differences that should be made clear.
A simple example of preprocessor variable usage is like this:
$brandColor: #F06D06;
.main-header {
color: $brandColor;
}
.main-footer {
background-color: $brandColor;
}
The above code would do nothing in a browser. The browser wouldn't understand the declarations and toss them out. Preprocessors need to compile into CSS to be used. This code would compile to:
.main-header {
color: #F06D06;
}
.main-footer {
background-color: #F06D06;
}
This is now valid CSS. The variable was part of the preprocessor language, not CSS itself. Once the code compiles, the variables are gone.
More recently, native CSS has started supporting CSS variables, or "CSS Custom Properties". It allows you to work with variables directly in CSS. There is no compiling.
A simple example of CSS custom property usage is like this:
:root {
--main-color: #F06D06;
}
.main-header {
color: var(--main-color);
}
.main-footer {
background-color: var(--main-color);
These two demos achieve the exact same thing. We were able to define a color once and use it twice.
Why would you use native CSS custom properties?
- You can use them without the need of a preprocessor.
- They cascade. You can set a variable inside any selector to set or override its current value.
- When their values change (e.g. media query or other state), the browser repaints as needed.
- You can access and manipulate them in JavaScript.
}
You could even re-set variables within media queries and have those new values cascade through everywhere using them, something that just isn't possible with preprocessor variables.
Comments
Post a Comment