Variables in Media Queries
CSS Using Variables in Media Queries
We now wish to alter a media query’s variable value.
Advice: Media Queries are used to specify distinct style guidelines for various screens, tablets, mobile phones, and other devices. See our Media Queries Chapter for additional information on media queries.
For the .container class, we first establish a new local variable called –fontsize. We have 25 pixels set as its value. The .container class farther down is where we use it after that. Next, we write a @media rule that states, “Change the –fontsize variable value of the .container class to 50px when the browser’s width is 450px or wider.”
Here is the complete example:
Example
/* 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;
}
}
Here’s another instance where the –blue variable’s value is altered in the @media rule:
Example
/* 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;
}
}
Browser Support
The numbers in the table specify the first browser version that fully supports the var() function.
CSS var() Function
Property | Description |
---|---|
var() | Inserts the value of a CSS variable |