CSS Custom Properties or CSS variables allow us to declare variables in our CSS files and use them inside our scope of choice. In this post I will go over some basic use cases for CSS custom properties and finish with an example that combines CSS custom properties and HTML custom attributes.
Declare
A CSS variable is made out of a property name and value:
:root{
--primary-color: dodgerblue;
}
Be sure to use the --
prefix before the property name.
Scope
Declaring CSS custom properties on the pseudo :root
class is considered a best practice. But you can also declare and use custom properties inside an element of your choice:
:root {
--gallery-grid-columns: 3;
--gallery-grid-gap: 15px;
}
.container {
--primary-color: dodgerblue;
}
The var()
Function
In order to use a CSS custom property we have to use the CSS var()
function:
:root {
--gallery-grid-columns: 3;
--gallery-grid-gap: 15px;
}
#gallery-container {
margin: auto;
display: grid;
grid-template-columns: repeat(var(--gallery-grid-columns), 1fr);
grid-gap: var(--gallery-grid-gap);
padding: 15px;
}
.container {
--primary-color: dodgerblue;
}
.container p {
color: var(--primary-color);
}
Example
My favorite use for CSS custom properties is using JS to manipulate them. I’ve created a pen with a working example that combines CSS custom properties, HTML custom attributes and js: