CSS Variables and Media Queries

Reuse values and adapt the layout to narrow screens.

CSS
:root {
  --accent: #0b5fff;
}

.button {
  background: var(--accent);
  color: white;
}

@media (max-width: 40rem) {
  .button {
    width: 100%;
  }
}

Explanation

A custom property such as --accent is defined once, often on :root, and read with var(--accent). A media query applies its rules only when its condition holds, so a button can become full width on small screens.

Explore the dry run
Guided walkthroughReady
1:root {
2 --accent: #0b5fff;
3}
4
5.button {
6 background: var(--accent);
7 color: white;
8}
9
10@media (max-width: 40rem) {
11 .button {
12 width: 100%;
13 }
14}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Define the --accent custom property once.—
—
Read the variable with var().—
—
The rules inside apply only on narrow screens.—
—
The button fills the width of its container.—
—