[Proposal] media(), like var() but for responsive values


#1

Right now, if you want to declare a responsive value on a declaration, you need to declare a new @media at-rule with the duplicated selector and property of your current declaration.

html {
  font-size: 16px;
}

@media {
  html {
    font-size: 20px;
  }
}

This module introduces a more efficient way of representing responsive values, removing all duplication.

html {
  font-size: media(16px, (min-width: 1200px) 20px);
}

This would accept single media conditions or custom media queries followed by single values, inspired by the css variables var() notation.

html {
  font-size: media(16px, --large-width 20px);
}

I’ve put together a small specification to describe what, why, and how the media() function does what it does, and I’ve created a PostCSS plugin to simulate this functionality. You may also test this functionality right now in CodePen.


#2

If we’re going to make media queries more useful, lets go all-in skip the media query syntax in favor of content queries.

I’ve never really cared about the size of the screen, but I’d love to be able to change layout based on the width of the parent element.

I don’t really know what this would look like for inline usage.


#3

Content queries have been discussed in the Element Queries thread. Let’s try to keep this discussion focused on the need it displays since it is much closer to being feasible for vendors then adding something auxillary on top with a lot of its own issues to deal with.


#4

This media queries shorthand seems quite a useful idea to avoid duplicating selectors and properties for small amounts of Cascading Style Sheets code. However, it would be inefficient for larger chunks as the browser would check the media query condition of every property in a selector instead of applying one @media rule to the whole selector and this rule would be repeated unnecessarily. This limits the use cases of the idea. Example:

<style>div>#lorem-ipsum>span[data-dolor-sit-amet]>a {color: red;}
@media screen and (min-width: 20em) {
  div>#lorem-ipsum>span[data-dolor-sit-amet]>a {color: white;}
  div>#lorem-ipsum>div {border: 0.1em solid grey; width: 2em; height: 2em;}
} /* The above could be changed to: */
div>#lorem-ipsum>span[data-dolor-sit-amet]>a {
  color: media(red, screen and (min-width: 20em) white);
} div>#lorem-ipsum>div {border: 0.2em solid grey;
  border-width: media(0.2em, screen and (min-width: 20em) 0.1em);
  width: media(1em, screen and (min-width: 20em) 2em);
  height: media(1em, screen and (min-width: 20em) 2em);
}</style>

Another potential addition to the media CSS function would be allowing multiple queries - so the first item in the comma separated list is the initial property value and the following items are media queries followed by property values (separated by a space).