Flash cards
Review the key moves
What is the main idea behind CSS Variables in Media Queries?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
--___-bg-color: #1e90ff;Put the learning moves in the order that makes the concept easiest to apply.
Media Queries are about defining different style rules for different devices (screens, tablets, mobile phones, etc.). You can learn more Media Queries in our Media Queries Chapter .
Now we want to set one variable value for screens below 450px wide, and another variable value for screens above 450px wide.
Here, we first declare a new local variable named --fontsize for the .container class. We set its value to 20 pixels. Then, we create a @media rule that says "When the browser's width is 450px or wider, change the --fontsize variable value of the .container class to 40px.":
Example
:root {
--primary-bg-color: #1e90ff;
--primary-color: #ffffff;
}
body {
background-color: var(--primary-bg-color);
} .container {
--fontsize: 20px;
color: var(--primary-bg-color);
background-color: var(--primary-color);
padding: 15px;
font-size: var(--fontsize);
} .container h2 {
border-bottom: 2px
solid var(--primary-bg-color);
}
@media screen and (min-width: 450px) { .container {
--fontsize: 40px;
}
}Live preview
Here is another example where we also change the value of the --primary-bg-color variable in the @media rule:
Example
:root {
--primary-bg-color: #1e90ff;
--primary-color: #ffffff;
}
body {
background-color: var(--primary-bg-color);
} .container {
--fontsize: 20px;
color: var(--primary-bg-color);
background-color: var(--primary-color);
padding: 15px;
font-size: var(--fontsize);
} .container h2 {
border-bottom: 2px
solid var(--primary-bg-color);
}
@media screen and (min-width: 450px) { .container {
--fontsize: 40px;
}
:root {
--primary-bg-color: lightblue;
}
}Live preview
CSS var() Function
| Function | Description |
|---|---|
| var() | Inserts the value of a CSS variable |