Skip to main content

CSS Variables in Media Queries

Media queries let you set different style rules for different devices, such as screens, tablets, and phones. You can learn more about them in the Media Queries Chapter.

A useful trick is to change CSS variable values inside a media query. This way, the styles that use those variables will automatically update when the screen size changes.

Example

This example sets a local variable --fontsize to 20px for the .container class. Then a @media rule changes --fontsize to 40px when the browser window is 450px wide or more.

Prompt
Create a page that uses CSS variables for colors and font size. Define --primary-bg-color (#1e90ff) and --primary-color (#ffffff) in :root. Set a .container class with a local --fontsize variable of 20px. Use a @media rule to change --fontsize to 40px when the screen is 450px or wider.
Output: complete HTML page

Changing multiple variables

You can also change more than one variable inside a media query. This example changes both the --fontsize and the --primary-bg-color variables when the screen is 450px or wider.

Prompt
Create a page that uses CSS variables for colors and font size. Define --primary-bg-color (#1e90ff) and --primary-color (#ffffff) in :root. Set a .container with a local --fontsize of 20px. Use a @media rule at min-width 450px to change --fontsize to 40px and also change --primary-bg-color to lightblue in :root.
Output: complete HTML page

CSS var() Function

The var() function inserts the value of a CSS variable. You can read more about it in the CSS var() reference.