CSS Custom Properties

CSS Custom Properties

CSS Custom Properties are sort of like variables in JavaScript or another programming language. They allow us to define CSS rules that can be reused for multiple selectors.

Using custom properties solves two issues that often come when writing CSS.

First is repeating values.

You have probably had the experience of using one color several times in various parts of you stylesheet and then deciding to change that color. Then you have to read through all of the rules and find each time you used it. With custom properties, you can just change the original property value.

Second is using calculations to set style values.

This week we're going to focus on creating a color scheme for the web app. When designing a color scheme, the relationships between colors can be describes by number values. We can't recreate this in CSS, at least not in the past, but now we can use CSS custom properties.

Custom property definition

To create a custom property, the value is defined using a special CSS rule.

These rules can be written inside of any CSS selector, but often they will be found in a selector called :root.

The :root is a shortcut to the highest level node in the document hierarchy. For HTML, this will be the <html> node.

:root {
	--custom-prop: value;
}

div {
	prop: var(--custom-prop);
}

The way to take advantage of a custom property is in cases where a color is used in multiple cases.

:root {
	--main-color: #0d6345; /* dark green */
	--accent-color: #f277f0; /* pink */
}
#site-title {
	color: var(--main-color);
	border-bottom: 1px solid var(--accent-color);
}

a {
	color: var(--main-color);
}

a:hover {
	color: var(--accent-color);
}

Site Title

This setup makes it easier to make changes to the color scheme or to the way colors are applied.

This is a simple example, but imagine a more complex site with lots of rules applying colors to different components of the design. The level of simplicity remains using custom properties.

Defining colors.

:root { 
	--main-color: #0d6345;
	--accent-color: #f277f0;
}

Site Title

Applying colors.

#site-title {
	color: var(--main-color);
	border-bottom: 2px solid var(--accent-color);
}

Site Title

.menu a {
	color: var(--main-color);
}

.menu a:hover {
	color: var(--accent-color);
}

Site Title