Switching CSS Dynamically Without Javascript

Disclaimer: I’m sure that there are more efficient, cross browser ways of doing this, my intent is to simply share what worked for me…

One of the nice things I discovered about CSS3 is the ability to detect devices and swap CSS files automatically without any javascript. The following code will enable you to use a different CSS file based on the device:

<link rel=”stylesheet” media=”all and (max-device-width: 480px)” href=”iphone.css”>
<link rel=”stylesheet” media=”all and (min-device-width: 481px) and (max-device-width: 1024px)” href=”ipad.css”>
<link rel=”stylesheet” media=”all and (min-device-width: 1025px)” href=”ipad.css”>

Although I don’t use it in my app, there are also ways to detect which orientation the device is using (landscape or portrait) and to dynamically apply different stylesheets based on that. Here’s a link to more information on that topic…

So back to the code I did use – the first line sets the CSS for an iPhone / iPod Touch, the second line specifies the CSS for the iPad, and the third line is for webkit browsers – since I’m not really worried about optimizing things for desktop browsers, I chose to just point it to the same stylesheet as the iPad.

This entry was posted in CSS3. Bookmark the permalink.