Conditional CSS

Jeremy Keith’s article Conditional CSS has helped me with the CSS/JS split for media queries. Basically, you set a hidden content value on the body at different breakpoints and use JS to read that value. This technique is particularly helpful because of how Safari/Chrome don’t include scrollbar width for media queries where as Firefox and Opera do. (See Roger’s examination of this). This technique allows you to let CSS tell the JavaScript that a media query has become active and grab the value associated with that breakpoint. It prevents cases where if you tested only for width in your JavaScript, JavaScript would return a value indicating a media query should be active, when it still has ~15px before it is triggered in the CSS.

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

// JS
var viewport = window.getComputedStyle(document.body,':after').getPropertyValue('content');
// Expected: viewport = 'widescreen'
// In IE 9: viewport = '"widescreen"'

If you use this technique, be aware that some browsers include the quotation marks in the string. You could test specifically for these quotes and remove them, or you could test for the content’s value via indexOf:

if( size.indexOf("widescreen") !=-1 )