bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/CSS/Advanced Styling
CSS•Advanced Styling

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