CSS Variables and Media Queries
Reuse values and adapt the layout to narrow screens.
On this page
The concept
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.
Code example
CSS
:root {
--accent: #0b5fff;
}
.button {
background: var(--accent);
color: white;
}
@media (max-width: 40rem) {
.button {
width: 100%;
}
}Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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
| Step / line | What happens | State after step | Output 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. | — | — |
Behind the scenes
How CSS processes this code
The browser matches selectors, computes styles, and paints the result. CSS does not produce console output.