0
0
CssHow-ToBeginner · 3 min read

How to Use CSS Variables in Media Queries Easily

You can use 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.
css
@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.

css
:root {
  --breakpoint: 600px;
}

body {
  background-color: lightblue;
  font-family: Arial, sans-serif;
  padding: 20px;
}

@media (min-width: var(--breakpoint)) {
  body {
    background-color: lightcoral;
  }
}
Output
The page background is light blue on small screens and changes to light coral on screens wider than 600px.
⚠️

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.

css
/* 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 :root for global use.
  • Use var(--variable-name) inside media query conditions.
  • Ensure variables hold valid CSS length units.
  • Test responsiveness by resizing the browser.

Key Takeaways

Always define CSS variables used in media queries in the :root selector for global access.
Use var(--variable-name) inside media query conditions to reference CSS variables.
Ensure the variable value includes valid units like px, em, or rem for media queries to work.
Using CSS variables in media queries makes responsive design easier to maintain and update.