How to Use CSS Variables in Media Queries Easily
CSS variables inside media queries by referencing them with the var() function in your media query conditions. Define the variable in a root or parent selector, then use it in the media query like @media (min-width: var(--breakpoint)) to make your design responsive and easy to update.Syntax
Use the var(--variable-name) function inside the media query condition to reference a CSS variable. The variable must be defined in a selector that is accessible at the time the media query is evaluated, usually :root.
--variable-name: The name of your CSS variable.@media (min-width: var(--variable-name)): Media query using the variable.
@media (min-width: var(--breakpoint)) { /* CSS rules here */ }
Example
This example shows how to define a CSS variable for a breakpoint and use it inside a media query to change the background color when the screen is wider than the variable value.
:root {
--breakpoint: 600px;
}
body {
background-color: lightblue;
font-family: Arial, sans-serif;
padding: 20px;
}
@media (min-width: var(--breakpoint)) {
body {
background-color: lightcoral;
}
}Common Pitfalls
One common mistake is defining the CSS variable inside a selector that is not accessible when the media query runs, like inside a class or element selector. Variables used in media queries must be defined in :root or a global scope.
Also, media queries only accept certain types of values, so ensure your variable holds a valid length or unit like px, em, or rem.
/* Wrong: variable defined inside a class, won't work in media query */ .container { --breakpoint: 700px; } @media (min-width: var(--breakpoint)) { body { background-color: yellow; } } /* Right: variable defined in :root for global access */ :root { --breakpoint: 700px; } @media (min-width: var(--breakpoint)) { body { background-color: yellow; } }
Quick Reference
- Define CSS variables in
:rootfor global use. - Use
var(--variable-name)inside media query conditions. - Ensure variables hold valid CSS length units.
- Test responsiveness by resizing the browser.