If you have been writing CSS for a while, you must have at some point in time felt the need for variables. CSS custom properties are somewhat like CSS’s own implementation of variables. However, when used properly, they can be so much more than just variables.
Fully-fledged CSS Variables
After long being requested by developers, a draft for an interpretation of native variables for CSS was written. These are formally referred to as CSS custom properties, but are also sometimes referred to as CSS variables.
The current specification for native CSS custom properties covers all the same behaviors as pre/postprocessor variables. This enables you to store color codes, sizes with all of the known units, or just integers if needed (e.g., when a you need to use the same divisor or multiplier).
The syntax for CSS custom properties is a bit weird compared to other languages, but it makes a whole lot of sense if you compare their syntax with other features in the same CSS ecosystem:
Read more
CSS custom properties allow you to:
- Assign arbitrary values to a property with a name of your choice
- Use the var() function to use these values in other properties
Although support for CSS custom properties is a bit of a rocky path at the moment, and some browsers support them under flags that need to be activated or set to true beforehand, their support is expected to increase dramatically moving forward, so it’s important to understand how to use and leverage them.
One of the main advantages of using CSS pre/postprocessors are is that they allow for values to be stored in a keyword and have them scoped to a certain selector if necessary.
After long being requested by developers, a draft for an interpretation of native variables for CSS was written. These are formally referred to as CSS custom properties, but are also sometimes referred to as CSS variables.
The current specification for native CSS custom properties covers all the same behaviors as pre/postprocessor variables. This enables you to store color codes, sizes with all of the known units, or just integers if needed (e.g., when a you need to use the same divisor or multiplier).
:root { --color-black: #2e2e2e; } .element { background: var(--color-black); }
Read more