Andy Taylor

Andy Taylor

Media Queries are a Hack

Apr 6, 2013 — ianstormtaylor.com/media-quer...

Ian Storm Taylor puts forward the idea that Media Queries make writing modular CSS difficult:

The big buzzwords in CSS these days are “modular” and “responsive”—and for good reasons. But we’re still trying to achieve those goals with the wrong tool: Media Queries. What we actually need is a tool that doesn’t exist yet: Element Queries.

It’s a really interesting read. He proposes that to write modular CSS, the query should be based on the width (or other variable) of the element, not on the width of the screen. For example:

.widget (min-width: 300px) {
  font-size: 0.8em;
}

It’s a great proposal. But it also left me wondering how it would work in practice. I imagine nested elements wouldn’t be an issue:

.widget (min-width: 300px) ul {
  list-style: none;
}

But what if you needed to add a pseudo class selector?

.widget (min-width: 300px):hover ul {
  color: #888;
}

Does that break the syntax? Wouldn’t the Element Query need to be chained to the element? If so, while we’re throwing around proposals, could we make the syntax a little less verbose:

.widget(width>300px):hover ul {
  color: #888;
}

Multiple queries could be linked with an ampersand:

.widget(pixel-density>=2 & height<100px) {
  line-height: 1em;
}

Using Sass would make this both modular and self-contained:

.widget {
  font-size: 0.8em;
  &(pixel-density>=2) {
    &:after {
      content: 'Retina';
    }
  }
  &(width>300px) {
    font-size: 1em;
    &:after {
      content: 'Greater than 300px';
    }
    &(pixel-density>=2) {
      &:after {
        content: 'Greater than 300px and Retina';
      }
    }
  }
}

However they’re implemented, I’d love for Element Queries to become a reality.

Have a comment? @me on Twitter.