Custom properties for breakpoint debugging

Yesterday, I stumbled across Eric Meyer’s post on displaying CSS breakpoint information with generated content. It reminded me of a solution to a related problem that Jeremy Keith blogged about way back in 2012 – how to conditionally load content (via JavaScript) when a certain breakpoint is active.

I was one of the people who came up with a potential solution to Jeremy’s problem, using pseudo-elements to stash a bit of text on (for example) the body element, and then reading that data via JS, using window.getComputedStyle(el, '::after') etc.

It was a hack, but it definitely worked.

Eric has discovered pretty much the exact same solution, but instead of hiding the stashed piece of text, he’s showing it to get a visual clue as to which media query (out of a few possible candidates) is currently active. Smart!

Now to the fun part: I remember having a discussion with Jeremy at some point about how the proper way to communicate in this manner between CSS & JS would be Custom Properties. I blogged about that back in 2013, using the Media Query naming technique as an example.

The solution I proposed there makes perfect sense as a small improvement to Eric’s debugging trick. Using a custom property allows for much cleaner code when setting the ”named breakpoint” text.

body::after {
   content: var(--bp, 'narrow');
}

@media (min-width: 25em) {
  :root {--bp: '>=25em'}
}

The first use of the var() uses a fallback value that you can pass in if the --bp custom property is undefined in the current scope. Then, at each increasingly wide breakpoint, you could update the --bp value to something new.

I’ve put a quick demo on JSBin – wrapped in one of my favorite CSS one-liners which I first saw from Lea Verou (although I can’t remember exactly where):

@supports (--css: variables) {}

Ah, blogging. Not dead yet.