When trying to make Today’s Guardian work better on the iPhone I had a strange problem with the pages sometimes being too wide for the device. It took me a while to figure out the solution, and it seems a bit odd, but here’s what I found out.
I’ve made three simplified pages that demonstrate the problem and solution. The basic HTML on all three pages is the same, and looks like this:
<body> <div id="wrapper"> <p>Some paragraphs here...</p> <p>More text...</p> </div> </body>
The first example is here. The div#wrapper in this example has this style applied:
And, in common with many recommendations I’ve seen for getting websites to display properly on the iPhone, the page has this meta tag:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
This causes problems though, as the CSS’s set width seems to take precedence over that meta tag’s “width=device-width” and the page comes out too large. Here’s how it looks — the left shows the page in Safari on an iPhone 3G running iOS4, and the right shows the same page when saved to the Home Screen and opened from there:
OK, so we need to fix something. Apple’s Safari HTML Reference guide says this about that meta tag:
If your webpage is narrower than 980 pixels, then you should set the width of the viewport to fit your web content. If you are designing an iPhone-specific web application, you should set the width to the width of the device.
OK, so let’s try our same example page, with the same CSS, but with the viewport meta tag like this:
<meta name="viewport" content="width=600">
Here’s the second example, with the new meta tag, and here’s how it looks, again in Safari on the left, and opened from the Home Screen on the right:
That surprised me. It looks fine opened in Safari — everything fits on the page — but when you save the page to the Home Screen and open it, the page looks different, and no longer fits. Very odd, and I’ve no idea why.
I thought that the Today’s Guardian page, from which this example was derived, worked fine from the Home Screen before I upgraded to iOS4, although I’m not 100% sure. Maybe this is a new problem, unique to iOS4?
Either way, how do we fix it? How do we get a page fitting and filling the iPhone screen, width-wise, when viewed in Safari and when opened from the Home Screen?
There may be other solutions, but the one I found was to set the div’s max-width, rather than its width. So in this third example div#wrapper has this CSS:
And the viewport meta tag looks like this:
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
This seems to do the trick; here are screenshots, again in iOS4, showing the page in Safari and opened from the Home Screen:
That second example bothers me though; surely the page should look the same in Safari and when opened from the Home Screen? Why would they be different?