CSS Targeted Only to the IPhone

One of this blogs readers, Dan Humphrey, was helpful enough to let me know that the footer position, in the new design, was not behaving correctly on the iPhone. Sure enough, when scrolling in Safari on the iPhone a position:fixed element behaves like an absolutely positioned element in other browsers. I like the fixed header and footer, and do not want to remove them, but at the same time, I dont want my site looking bad on the iPhone. The solution then is to figure out a way to target a CSS file just for the iPhone. While, you could attempt to browser sniff on the client- or server-side, using HTML and IE conditional comments is a better practice:

Example 1: CSS Targeted to IPhone

<!--[if !IE]>-->
	<link media="only screen and (max-device-width: 480px)" href="/assets/css/iphone.css" type="text/css" rel="stylesheet" />
<!--<![endif]-->

I believe this was originally proposed by Jeremy Flint, in his article Designing for the iPhone. Looking at the link first, the important part is the media attribute. For the most part only browsers understand the keyword screen and modern browsers the keyword only. A new CSS3 selector, max-device-width, is used and only the iPhone has a value of 480px. This will prevent most older browsers and other mobile devices from serving the CSS file. However, there are versions of IE that will ignore the media attribute. For this reason the IE conditional comment is used:

Example 2: Standard IE Conditional Comment

<!--[if !IE]>
…
<![endif]-->

Unfortunately, only IE understands the IE conditional comment, and it is treated as a comment by other browsers. To serve the link in non-IE browsers we need to wrap the IE conditional comment with regular HTML comments, thereby causing non-IE browsers to ignore the IE conditional comment.

Example 3: Wrapped IE Conditional Comment

<!--[if !IE]>-->
…
<!--<![endif]-->

This way the <!--[if !IE]> and <![endif]--> are both inside HTML comments, so the conditional comments will be commented out by non-IE browsers. In IE, the conditional statement ignores the inside content, including the link and partial HTML comments.

Putting it all together (Example 1), you have HTML serving a CSS stylesheet only to the iPhone.

There isnt as good of a technique to target JavaScript. If you want to target JavaScript specifically to the iPhone, then wrap code targetting the iPhone with an if statment that checks the window.orientation property. This is a new property introduced for the iPhone.

Example 4: JavaScript for the iPhone

if (YAHOO.lang.isDefined(window.orientation) {
	…
}