CSS Tutorial
CSS Advanced
CSS Responsive
CSS Grid
Variables in Media Queries
Using Variables in Media Queries
Firstly, we’ll declare a new local variable named –fontsize for the .container class and set its value to 25 pixels. Then, it is used in the .container class. Then, A @media rule is created that defines “When the browser’s width is 450px or wider, change the –fontsize variable value of the .container class to 50px.”
Below is an example:
HTML
Using Variables in Media Queries
Lorem Ipsum
When the browser's width is less than 450px, the font-size of this div is 25px. When it is 450px or wider, set the --fontsize variable value to 50px. Resize the browser window to see the effect.
CSS
/* Variable declarations */
:root {
--blue: #1e90ff;
--white: #ffffff;
}
.container {
--fontsize: 25px;
}
/* Styles */
body {
background-color: var(--blue);
}
h2 {
border-bottom: 2px solid var(--blue);
}
.container {
color: var(--blue);
background-color: var(--white);
padding: 15px;
font-size: var(--fontsize);
}
@media screen and (min-width: 450px) {
.container {
--fontsize: 50px;
}
}
Output
Using Variables in Media Queries
Lorem Ipsum
When the browser's width is less than 450px, the font-size of this div is 25px. When it is 450px or wider, set the --fontsize variable value to 50px. Resize the browser window to see the effect.
Below is an example in which the value of the –blue variable in the @media rule is changed:
HTML
Using Variables in Media Queries
Lorem Ipsum
When the browser's width is 450px or wider, set the --fontsize variable value to 50px and the --blue variable value to lightblue. Resize the browser window to see the effect.
CSS
/* Variable declarations */
:root {
--blue: #1e90ff;
--white: #ffffff;
}
.container {
--fontsize: 25px;
}
/* Styles */
body {
background-color: var(--blue);
}
h2 {
border-bottom: 2px solid var(--blue);
}
.container {
color: var(--blue);
background-color: var(--white);
padding: 15px;
font-size: var(--fontsize);
}
@media screen and (min-width: 450px) {
.container {
--fontsize: 50px;
}
:root {
--blue: lightblue;
}
}
Output
Using Variables in Media Queries
Lorem Ipsum
When the browser's width is 450px or wider, set the --fontsize variable value to 50px and the --blue variable value to lightblue. Resize the browser window to see the effect.