bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/CSS/Advanced Styling
CSS•Advanced Styling

CSS Variables in Media Queries

Flash cards

Review the key moves

1/4
Core idea

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.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

--___-bg-color: #1e90ff;
3Order

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.
CSS var() Function
CSS Variables in Media Queries

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

Formatted code
: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

Formatted code
: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

FunctionDescription
var()Inserts the value of a CSS variable

Previous

CSS Variables and JavaScript

Next

CSS @property Rule