Reusable media queries with headcase.js
After reading a few articles about reusable media queries, and writing the previous post, something clicked and I thought that it should be a no brainer to read media queries from the head of the document and re-evaluate them on resize events. So here’s headcase.js.
This article by Matt Wilcox pretty much explains the idea, but basically, headcase lets you define your breakpoints once in the document head, and reuse them in css & javascript. Here’s an example.
<head>
<meta name='case' content='wide' media='(min-width:750px)' />
<style type="text/css">
.wide body {
font-size: 2em
}
</style>
</head>
By defining media queries in the head of your document, they’ll be reusable in css and javascript via classes on the html element, and events in javascript. No need to ever copy & paste the same query in multiple places in your css file. In javascript, you can use caseChange events to respond to media changes. I wish this was standard stuff in browsers. As Matt Wilcox pointed out on twitter, headcase is polyfill for a potential html feature. The caveat is that using headcase for media queries makes media queries dependent on javascript.
I don’t wan’t to just repeat the whole readme here, so head on to github to try it out.
As a side note, it’s strange how most places I’ve seen headcase linked, “<head>” in the description gets eaten by the system and just disappears. Makes the description look a bit off.