Start learning free

LESSON 20 OF 161 · FRONTEND: CSS

Variables in JavaScript

Practice

Your heading, your prices and your links should share one brand color. If you write the color into three rules, changing the brand means finding and editing all three. A variable (a custom property) stores the value in one place.

At the start, the h1 rule in styles.css is empty and the second .card rule has no margin-bottom: the #0a7 and the 16px from the last lesson are gone, so the heading inherits #333 from body. You write both back in this lesson, this time with variables.

A variable is a property you name yourself, starting with two dashes. You set it like any other property, usually on :root, the html element. Variables are inherited, so one set on :root reaches every element. var(--name) uses its value:

:root {
  --muted: #999;
}

footer p {
  color: var(--muted);
}

The footer's paragraph gets color: #999. To change it, and every other rule that uses --muted, you edit only the line in :root. A variable that has no value yet gives var() nothing to put in its place: the check then prints var(--brand) as it is, not a color.

When your file is done, the check must print:

h1 "Corner Shop"
  color: #06c   <- h1
p.price "$12"
  color: #06c   <- .price
a "Home"
  color: #06c   <- nav a
li#mug.card "Mug $12 Buy"
  margin-bottom: 16px   <- .card

Your task: below the * rule, add a :root rule with --gap: 16px, and use var(--gap) for the card's margin-bottom. Then use var(--brand) for the color of h1, .price and nav a. Last, give --brand its value, #06c, in :root.


Assignment
Follow the Coding Tutorial to store the shop's spacing and brand color in two variables on :root, and use them in four rules of styles.css.


Hint
A variable's name starts with two dashes, both where you set it and inside var(). If the check still prints var(--brand) at the end, --brand has no value in :root, or it is spelled differently there.


STEP 1 OF 7
    Ctrl + Enter to check

    Css Variables in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free