Using media queries to hide CSS3 from older browsers

When working around bugs and different levels of support in various browsers, a common approach is using conditional comments to target certain versions of Internet Explorer. Come to think of it, it’s pretty rare to need to fix something for an older version of any other browser. People who do not use IE tend to upgrade quicker and CSS-related bugs in other browsers tend to be less severe than in IE, especially compared to IE7 and older.

Anyway, while working on a lot of responsive layouts lately I’ve started using an approach that I’ve found reduces the risk of more advanced CSS, especially CSS3, tripping up older browsers. I simply wrap any CSS that I know won’t work at all or may only half-work in a very basic media query, like this:

@media only screen {
	/* "Advanced" CSS2 and CSS3 goes here */

From the Media Queries specification:

The keyword ‘only’ can also be used to hide style sheets from older user agents. User agents must process media queries starting with ‘only’ as if the ‘only’ keyword was not present.

Since only browsers that understand media queries will apply the CSS inside that rule, I can use modern CSS without needing to worry as much about fallbacks or bugs. It’s like creating a safe bubble of excellent CSS support. I normally put this @media rule before the @media rules that target various viewport widths, so I can use it as a starting point for making the layout responsive.

Browser usage numbers may differ, of course, but in practice this mostly means hiding CSS from IE8 and older. The market share of non-Media Query-supporting versions of other browsers tends to be negligible. Besides, they will still the same fully acceptable but non-responsive layout that oldIE gets.

Posted on June 26, 2012 in CSS