Bite-sized CSS & HTML nuggets

Easily checking in JavaScript if a CSS media query has been executed

For quite a while I have been looking for a way to “mirror” my CSS media queries in JavaScript, but without duplicating the actual queries. Of course, you can use matchMedia to evaluate a media query in JavaScript, but then you have to maintain your breakpoints in two places – not ideal.

Paul Hayes devised a clever method in his fork of the match­Me­dia poly­fill, using transitions on dummy elements and watching for the tran­si­tio­nEnd event in JavaScript. But a truly simple solution – one that doesn’t really need watching for resize events – was still lacking.

Fortunately Jeremy Keith turned to his readers for help, and together they came up with a delightfully straightforward technique:

@media (min-width: 45em) {
    body:after {
        content: 'widescreen';
        display: none;

Which basically doesn’t do anything, except that you can check for it in Javascript:

var size = window.getComputedStyle(document.body,':after').getPropertyValue('content');
if (size == 'widescreen') {
    // go nuts


Shorter media queries

As tweeted by Mathias Bynens a few months ago:

Most of the time, there’s no need to limit your media queries to screen media only.

Indeed, usually your media queries should apply to all media types, so instead of this:

@media screen and (min-width: 500px) { ... }

You can do this:

@media all and (min-width: 500px) { ... }

Even better, the spec says the all keyword can even be left out – it’s the implied default – leaving you with this:

@media (min-width: 500px) { ... }

Never miss an opportunity to shave a few bytes off your code and type a few characters less!