Middle
What is the difference between variables in CSS and variables in preprocessors?
sobes.tech AI
Answer from AI
Variables in preprocessors (Sass, Less, Stylus) are processed before compilation into CSS. They allow storing values, using them in calculations, and applying them with directives (@mixin, @function), making CSS more dynamic and modular.
CSS variables (custom properties), declared using the syntax --variable-name, are processed by the browser at runtime. Their values can be changed with JavaScript, which is useful for creating dynamic themes or changing styles depending on the element's state.
| Characteristic | Variables in preprocessors | CSS variables (custom properties) |
|---|---|---|
| Processing | At precompilation stage | In the browser (runtime) |
| Change in JS | Impossible | Possible |
| Scope | Depends on preprocessor (block, global) | Depends on the definition location (global, within a selector) |
| Usage | Declared with symbols ($, @) |
Declared with -- |
Example of using CSS variables in the browser:
:root {
--main-color: blue; /* Declaring a global CSS variable */
}
.element {
color: var(--main-color); /* Using the CSS variable */
}
const element = document.querySelector('.element');
element.style.setProperty('--main-color', 'red'); /* Changing CSS variable with JS */