Arno's Blog

How to optimize a web page for the iPhone

There are a few simple changes you can make to a web page to get it to display better on an iPhone (or iPod Touch). I've talked about this elsewhere but I've applied it to the layout of this blog as well. Try it out (or look at the screenshots below)!


What are those changes, you ask?

First, in the <head> section, add:


<meta name="viewport" content="width = device-width" />


The viewport tag will ensure that the page is taking the full width of the iPhone, without any horizontal scrolling.


Next, add this to the <body> tag:


<body onload="setTimeout(function() { window.scrollTo(0, 1); }, 100);">


This will make sure that once the page is loaded the Safari toolbar at the top will get scrolled out of view so that as much as your web page as possible is displayed on the screen.


Finally, you'll want a custom stylesheet for the iPhone. My stylesheet is built-in into my blogging template (i.e. not an external file), so I added another <style> tag that overrides and modify the style defined in my "default" stylesheet:


<style media="only screen and (max-device-width: 480px)" type="text/css">


/* Override style definitions as appropriate */
body {
  width:480px;
  background:#f00
  margin:0;
  padding:0;
  font: large "Trebuchet MS",Trebuchet,Arial,Verdana,sans-serif;;
  color:#333;
 }

/* etc... */

.not-iPhone {display:none;}

</style>


There are other ways to accomplish the same thing that are described in Apple's documentation


Note that I define a #not-iPhone class so that I can hide any content that I don't want to display on the iPhone, such as large images or content type not supported on the iPhone.


In the iPhone stylesheet, I've changed the layout so that it fits the smaller screen of the iPhone (480 px). For example, I moved the sidebar at the bottom of the page, instead of on the right. To take advantage of the limited real estate, I've removed some margins. I have also simplified the layout and removed some of the background textures I used on when not on the iPhone. Finally, I used a resized version of the header image (resized to 480 px wide), so that it loads a bit faster.




2 comments:

From OpenID thinkdrastic:

Some nice tips in there.

One thing though: #not-iPhone isn't a class, it's an id -- meaning it can only be used once per page. I suspect you meant .not-iPhone :)

25 June, 2008 03:31  
From Blogger arno:

@thinkdrastic: good point, that's what I meant. I'll fix the post... Thanks!

25 June, 2008 14:21  

Post a Comment

Links to this post:

Create a Link

<< Home