CSS native variables not working in media queries

前端 未结 7 1479
情书的邮戳
情书的邮戳 2020-11-30 19:57

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)) {         


        
7条回答
  •  悲哀的现实
    2020-11-30 20:47

    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 element, and from there be inherited to other elements. But a media query is not an element, it does not inherit from , so it can't work.

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

提交回复
热议问题