W3C home > Mailing lists > Public > www-style@w3.org > April 2015

Re: [css-variables][mediaqueries] Allow var() in media queries?

From: Glen Huang <curvedmark@gmail.com>
Date: Wed, 8 Apr 2015 18:30:22 +0800
Cc: www-style list <www-style@w3.org>
Message-Id: <470E8733-0068-46DF-8959-3ED7C151A7FE@gmail.com>
To: "Tab Atkins Jr." <jackalmage@gmail.com>
@custom-media mitigates the duplication issue, but still not perfect in case like this:

:root {
	--horizontal-nav-width: 600px;

@custom-media --horizontal-nav-fits (width >= var(--horizontal-nav-width))
@media (--horizontal-nav-fits) {
	.nav {
		width: var(--horizontal-nav-width);
		margin: 0 auto;

In this case, I design the media query specifically for the navigation. So it would be great if I can reuse the dimension in media query. Otherwise I have at least two places to edit when, for example, the number of navigation links change, and the allowed width is changed.

The recursion problem can be solved either as mentioned by Andrea (variables used in media query aren't live, they only resolve to the custom properties of the top level :root rule), or as mentioned by me (variables used in media query resolve to the custom properties of an at-rule that can’t be specified in a media at-rule).

Not sure if these two approaches are feasible.

> On Apr 8, 2015, at 8:30 AM, Tab Atkins Jr. <jackalmage@gmail.com> wrote:
> On Sat, Apr 4, 2015 at 12:59 AM, Glen Huang <curvedmark@gmail.com> wrote:
>> Does this do what I think it does?
>> ```css
>> :root {
>>        --page-width: 768px;
>> }
>> @media (min-width: var(--page-width)) {}
>> ```
>> If not, is it because media queries don’t inherit properties from the :root element? If that’s the case, can we add a selector to select a special element that the :root element and media queries will all inherit from?
>> When you design the media query break points according to certain element dimensions, being able to use variables in media queries can be very helpful.
> The var() function, when used on an element, just replaces itself with
> the value of the given custom property on the same element.  @media
> rules aren't referring to any element, so they don't have any
> properties at all, let alone custom properties.
> You could let it refer to the value of the custom properties on the
> root, as you suggest, but as Cameron says, it makes it way too easy to
> get into bad loop situations.
> What you want are just Custom Media Queries
> <http://dev.w3.org/csswg/mediaqueries/#custom-mq>.  That way you could
> define something like:
> @custom-media --large-page (width >= 768px);
> @custom-media --small-page (width < 768px);
> @media (--large-page) { ... }
> ~TJ
Received on Wednesday, 8 April 2015 10:30:54 UTC

This archive was generated by hypermail 2.4.0 : Friday, 25 March 2022 10:08:53 UTC