RedJohn RedJohn - 1 year ago 116
CSS Question

CSS native variables not working in media queries

I am trying to use CSS variables in media query and it does not work.

:root {
--mobile-breakpoint: 642px;

@media (max-width: var(--mobile-breakpoint)) {


Answer Source

From the spec,

The var() function can be used in place of any part of a value in any property on an element. The var() function can not be used as property names, selectors, or anything else besides property values. (Doing so usually produces invalid syntax, or else a value whose meaning has no connection to the variable.)

So no, you can't use it in a media query.

And that makes sense. Because you can set --mobile-breakpoint e.g. to :root, that is, the <html> element, and from there be inherited to other elements. But a media query is not an element, it does not inherit from <html>, so it can't work.

This is not what CSS variables are trying to accomplish. You can use a CSS preprocessor instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download