CSS Using Variables in Media Queries

Using variables in media queries

Now, we want to change the variable value in the media query.

Tip:Media queries are intended to define different style rules for different devices (displays, tablets, mobile phones, etc.). You can learn more about media queries in the 'Media Queries' chapter.

In this example, we first declare a new local variable named --fontsize for the .container class. We set its value to 25 pixels. Then we use it further within the .container class. Then, we create a @media rule with the content 'When the browser width is 450px or wider, change the --fontsize variable value of the .container class to 50px.'

Here is the complete example:

Example

/* Variable declarations */
:root {
  --blue: #1e90ff;
  --white: #ffffff;
}
.container {
  --fontsize: 25px;
}
/* Style */
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;
  }
}

Try It Yourself

This is another example where we also changed the value of the --blue variable in the @media rule:

Example

/* Variable declarations */
:root {
  --blue: #1e90ff;
  --white: #ffffff;
}
.container {
  --fontsize: 25px;
}
/* Style */
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;
  }
}

Try It Yourself

Browser Support

The numbers in the table indicate the first browser version that fully supports this property.

Function
var() 49.0 15.0 31.0 9.1 36.0

CSS var() Function

Function Description
var() Insert the value of the CSS variable.