bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/CSS/Advanced Styling
CSS•Advanced Styling

CSS Variables in Media Queries

Overview

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;

Formula

-- primary - color:
#ffffff;
}
body {

Formula

background - color:
var(--primary-bg-color);
}.container {
--fontsize: 20px;
color: var(--primary-bg-color);

Formula

background - color:
var(--primary-color);
padding: 15px;

Formula

font - size:
var(--fontsize);
}.container h2 {
border-bottom: 2px solid var(--primary-bg-color);
}

Formula

@media screen and (min - width:
450px) {.container {
--fontsize: 40px;
}
}

Formula

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;

Formula

-- primary - color:
#ffffff;
}
body {

Formula

background - color:
var(--primary-bg-color);
}.container {
--fontsize: 20px;
color: var(--primary-bg-color);

Formula

background - color:
var(--primary-color);
padding: 15px;

Formula

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;
}
}

CSS var() Function

Function

Description var()

Inserts the value of a CSS variable

Previous

CSS Variables and JavaScript

Next

CSS Variables Code Challenge