Custom Properties
Custom properties (also referred to as CSS variables) contain values that are referenced in other declarations through the use of the var()
function.
Websites often have large amounts of repeated values whether a breakpoint value, or style values for a theme. Custom properties offer authors the ability to declare values once and reuse multiple times. This reduces mistakes and increases quality while greatly reducing the maintenance burden of updating multiple declarations when editing is required.
General attributes of a custom property include:
- Custom properties are scoped to the elements they are declared on and are subject to cascade and inheritance
- All custom properties begin with two dashes
--
and are case sensitive - If a custom property is declared multiple times standard conflict resolution rules apply
Define a Custom Property
We define a custom property as follows:
:root {
—-body-copy-color: green;
}
We scope the —body-copy-color
custom property to the :root
pseudo-element to make it available across most elements.
Use a Custom Property
To use a custom property, we call the var()
function and pass in the custom property name. The function will return the value declared when we defined the custom property.
body p {
color: var(--body-copy-color);
}
Further Review
Review the following material and be sure to download the lesson file.
- Read Using CSS custom properties (variables) - CSS: Cascading Style Sheets | MDN
- Read CSS Variables — No, really! - Dev Channel - Medium
See Also
- A Complete Guide to Custom Properties
- Breaking CSS Custom Properties out of :root Might Be a Good Idea | CSS-Tricks
- Making Custom Properties (CSS Variables) More Dynamic | CSS-Tricks
Lesson File
CSS Best Practices Lesson File