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