Polyfill for @media range syntax

| permalink | css

Turns out you can nest media queries in CSS, which means you can achieve @media (640px <= width < 1024px) logic in browsers without @media range syntax support by writing

@media (min-width: 640px) and (max-width: 1024px) {
  @media not (width: 1024px) {
    /* style */
  }
}

So, why is this useful?

Because it lets you elegantly define gapless range with older browsers.

Without using nested @media not query, you have two options:

Override

Define @media range with one end open, and override the values you've set using the next @media range. This becomes unwieldy pretty quick.

Pixel splitting

Define range using pixels, for example:

@media (min-width: 640px) and (max-width: 1023px) {
    /* style */
}
@media (min-width: 1024px) {
    /* style */
}

People ran into problem with this, due to pixels in browser being virtual pixels, not actual screen pixels, so they had to resort to going into decimal points (such as Bootstrap):

@media (min-width: 640px) and (max-width: 1023.98px) {
    /* style */
}
@media (min-width: 1024px) {
    /* style */
}

Now this is just hackish and ugly, and could break in the future.

However, with nested @media not query, the issue is solved elegantly.