CSS Variables are formally known as "Custom Properties" because they’re similar to regular CSS properties and set using custom property notation.
Declaring & Using Variables
To use CSS variables in your stylesheet, you declare the variable inside a selector using custom property notation. Then you reference the variable (or custom property name) using the CSS var()
function.
Declaring
:root {
--proprty-name: value;
}
Using
.selector {
width: var(--property-name);
}
A more elaborate example
Declaring
:root {
--color-primary: #278da4;
--color-secondary: #b13c69;
--color-bg: #3acec2;
--color-bg-light: #009fe1;
--gradient: var(--color-bg-light),
var(--color-bg);
--font-stack-primary: 'Raleway', sans-serif;
--font-stack-secondary: 'Bree Serif', serif;
--max-width: 1000px;
--gutter: 12px;
}
Using Variables Responsively
.ball {
--animate: bounce;
width: 100px;
height: 100px;
border-radius: 50%;
background-color: tomato;
animation: var(--animate) 1.15s ease-in-out infinite;
}
@media (min-width: 576px) {
.ball {
--animate: slide;
}
}
@media (min-width: 768px) {
.ball {
--animate: diag;
}
}
@keyframes bounce {
50% { transform: translate3d(0,80vh,0); }
}
@keyframes slide {
50% { transform: translate3d(76vw,0,0); }
}
@keyframes diag {
50% { transform: translate3d(86vw,80vh,0); }
}
Using Variables Inline
You can change the value of a variable for a specific HTML element.
<a href="#" class="btn btn-info" style="--color-primary: #fff">
Learn more
</a>
Note: Finally, variable names are case sensitive.