Re-usable queries


#1

How do we reuse queries?

For example, we might want to style individual components, in separate files, and we want to use the same queries inside the components. That’s why in theory I like CSS in JS because it’s super easy to reuse functions.

For example, suppose we have a media query:

@media (max-width: 12450px) { ... }

then in five other components I want to style things based on the same (possibly long query):

@media (max-width: 12450px) { ... }
@media (max-width: 12450px) { ... }
@media (max-width: 12450px) { ... }
@media (max-width: 12450px) { ... }
@media (max-width: 12450px) { ... }

If we want to update the query, we have to do it in all places, which means more maintenance and chance of error. Sass/Stylus/etc solve this for us.

It’d be great to somehow be able to reuse a query (and same with @tomhodgins@element queries). F.e.:

@media:name(max) (max-width: 12450px) {  /* some styles here */ }

Then in other places

@media:use(max)  {
  /* styles for a component, perhaps an element query for scoping. Or add more globals styles, etc. */
}

#2

Custom media queries are already in the spec.

They can be used as in the example on that page:

@custom-media --narrow-window (max-width: 30em);

@media (--narrow-window) {
  /* narrow window styles */
}
@media (--narrow-window) and (script) {
  /* special styles for when script is allowed */
}
/* etc */

#3

Ah, cool. I can’t find any information on browser support. I’m guessing this means zero support?


#4

That’s correct AFAIK. I use PostCSS regularly, which (unsurprisingly) has a plugin for it.


#5

Browsers have supported XPath since Internet Explorer 3.5 in 1997/8.

XPath 1 is supported natively in all major browsers.


#6

@liamquin I was referring to Custom Media about the browser support in my last comment, but that’s nice to know. Thanks!


#7

Ah, sorry for my confusion.