Bulletproof CSS3 media queries
Why is that?
CSS3 media queries are very handy to target various devices with various monitor (screen) size. With the help of the CSS3 media queries we can have site optimized for iPhone and other mobile devices, with the same solution we can have site optimized for iPad and all other tablets . This CSS solution will be much more cheaper than building new mobile web site something like http://m.somewebsite.com or http://ipad.somewebsite.com .
Can we start using the CSS3 media queries today?
Yes we can!
The main problem of the CSS3 media queries is they will not work in the older browsers .
CSS3 media queries will not work in IE8 (and lower) also browsers lower then Firefox 3.5, Safari 3, and Opera 7. Basically the main problem is IE and the older version of Firefox.
For the mobile web browsers this solution should work for the modern webkit and opera browsers that support CSS3 media queries.
Here is the solution:
<!-- Big screen --> <link rel="stylesheet" type="text/css" href="CSS/main.css" media="screen and (min-device-width: 800px)" /> <!-- Tablet pc --> <link rel="stylesheet" type="text/css" href="CSS/tablet.css" media="screen and (min-device-width: 481px) and (max-device-width: 799px)" /> <!-- Mobile --> <link rel="stylesheet" type="text/css" href="CSS/mobile.css" media="only screen and (max-device-width: 480px)" /> <!-- If is lower than IE9 use conditional comments --> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="CSS/main.css" media="all" />
We have one CSS for mobile browsers with max screen of 480px. For the older phones who doesn’t support CSS3 media queries we can alternately add media="handheld" CSS.
For the monitor size from 481px to 799px (iPad and other tablets) we will have other CSS.
In the case of the monitors from 800px and more we will have the main CSS.
All current IE browsers don’t support media queries but we can easily fix this by using IE Conditional Comments
Other important thing the browsers will probably download only one ( <link type="text/css" … /> ) stylesheet and ignore all the other CSS. In this way the browser will not load unnecessary CSS.
I’m not 100% sure that all the browsers will ignore the unnecessary CSS probably the browser speed experts like Steve Souders and Stoyan Stefanov may know little more about this.
Demo of this solution
Download the code
Conclusion: CSS3 Media Queries are cheap and easy way to optimize your web site for various devices. With this solution you can safely cover 99% of PC browsers and the modern mobile browsers (iPhone, iPad, Android, new webkit BlackBerry and the new Opera Browsers).
Other useful resources:
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)