Store Colors in Custom Properties

In Ask DevTools Why a Rule Fails, you tracked down rules that didn’t apply. The rules that do apply have a different problem. They repeat the same values.

The garden’s green, oklch(0.447 0.116 152.7), appears five times in events/events.css: in h1, a, h2::before, .family-friendly, and Kofi’s h2.family-friendly. Its darker shade appears three times. If Rosa ever asks for a slightly different green, you’ll have to find every copy and hope you didn’t miss one.

A programmer’s answer is to give the value a name and use the name everywhere, the way you’d declare a constant. CSS has a feature for this, and in this lesson, you’ll use it to keep the garden’s colors and text sizes in one place. You’ll also be able to predict which value the name gives on any element of the page. Start with a new request from Rosa.

Give the Garden’s Green a Name

Rosa would like the garden’s name, the first line of the header on the events page, in the garden’s green. It’s gray for now, because the p rule colors every paragraph #737373. Pasting the oklch() value a sixth time would work, but it would make the copying problem worse, so this time, you’ll name the value first.

A custom property is a property whose name you choose. Its name starts with two hyphens, and you declare it inside a rule like any other property: --green: oklch(0.447 0.116 152.7);. The browser doesn’t style anything with it. It only stores the value.

To use it, you write var(--green) where a value goes, and the browser puts the stored value in its place.

You need the green in the header, so declare it there. Treat this as a first attempt. Before you build on it, you’ll test how far the name reaches. Add two rules at the end of events.css, one for the header and one for its paragraph:

Language: CSS Filename: events/events.css
header {
  --green: oklch(0.447 0.116 152.7);
}

header p {
  color: var(--green);
}

Save, and the garden’s name turns green. The header p selector scores (0, 0, 2), so it beats the p rule’s (0, 0, 1), as Find Out Which Rule Wins showed.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.