iPhone CSS—tips for building iPhone websites

With the rapid rise in mobile browsers, it has probably never been more important to ensure your sites can be handled on these platforms. By far one of the most popular such browsers is Mobile Safari on the iPhone—this is one of the easiest browsers to develop for: it runs on Webkit (meaning a lot of rich CSS3 support) and it’s only ever on one resolution and on one OS.

N.B. This article addresses iPhone development and iPhone development only. There is no reason why you cannot or should not develop for other mobile devices and platforms, Apple or otherwise. This just happens to be an iPhone only post.

The practical upshot of this is that you need to do no cross-browser testing, and can use all the CSS3 you like. This post will show you some of the basics of developing and designing websites for the iPhone and Mobile Safari.

To start

The first thing to remember when developing a site to be displayed on an iPhone is that it is very similar to designing a print stylesheet. You need to linearise everything. Make sure you have one column and everything is read in one line—straight from top to bottom. This will also put your markup writing skills to the test.

Some people don’t agree with browser sniffing, but you need to detect the iPhone somehow.

This first bit of code is a PHP browser sniffing snippet, the actual CSS we’ll use is not brought through via any server side code, we’ll use some CSS media queries for that. What we’ll use this code for is serving the markup with an iPhone specific meta tag and to shorten the current page’s title.

<?php
  $browser = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
    if ($browser == true){
    $browser = 'iphone';
  }
?>

What the above code does is sees if the user agent contains any instance of ‘iPhone’ using the strpos PHP function. Place this piece of code at the very top of your header include, before any other markup. In order to action something if the browser is an iPhone, simply use the following bit of PHP logic in the place you want it to be initiated:

<?php if($browser == 'iphone'){ ?>DO THIS<?php } ?>

We want people to save your site to their home screen…

Now, to put that snippet to use. We want to do two things with this little piece of PHP.

Saving to the homescreen—shortening the page title

An iPhone screenshot of the CSS Wizardry home screen icon

First off, we’d like users to be able to save a link to your site on their home screen, this is simple enough, they simply need to select to do so from within the browser. However, if you look at the title of my home page alone, it’s quite long: CSS Wizardry—CSS, Web Standards, Typography, and Grids by Harry Roberts. This would never fit underneath an icon without being shortened, so we need to serve a different title to the iPhone only. To achieve this we us the PHP snippet like so:

<?php if($browser == 'iphone'){ ?>
  <title>Short iPhone only title</title>
<?php }else{ ?>
  <title>Regular title</title>
<?php } ?>

Now, both when browsing and saving your site to their home screen, a user will only ever see the shortened version.

The home screen icon

Actually making the icon is very simple. All you need to do is upload a 57×57px icon (usually a larger version of your favicon) to your server root. The icon must be named apple-touch-icon.png, and the iPhone will sort the rest out. See my icon.

Stopping user pinch-zooming

The second use for the PHP snippet is to serve the iPhone a meta tag which disables the user pinch-zoom that Mobile Safari offers:

<?php if($browser == 'iphone'){ ?>
  <meta name="viewport"
  content="width=device-width,
  minimum-scale=1.0, maximum-scale=1.0" />
<?php } ?>

This means that, once we’ve linearised the content and sorted the font sizing, the user will only ever have to traverse down your page, much like a native app.

Beginning styling

Some developers prefer to redirect iPhone users to a totally different version of the site—we won’t be doing that.

We could use the PHP snippet to serve the iPhone a whole new stylesheet, or even send the user to a whole new site, rather like Twitter does (m.twitter.com). However, there’s a simpler way to do it using some CSS media queries. The advantage of this is that you’re simply reusing old content and pre-written markup, and only ever using one CSS file.

The first thing you need to do is make sure the HTML link element that points to your main stylesheet does not have a media attribute:

<link rel="stylesheet" type="text/css" href="/path/to/style.css" />

Next, we’re going to use Quick Tip #15 that I wrote on my Quick Tips page. This means that we can just add our iPhone styles directly onto the end of the main stylesheet, and inherit all the styles set for desktop viewing:

/*--- Main CSS here ---*/

/*------------------------------------*\
	IPHONE
\*------------------------------------*/
@media screen and (max-device-width: 480px){
/*--- iPhone only CSS here ---*/
}

Now any CSS before the media query will be used across all platforms, but anything between the query will be used by any screen media with a maximum screen size of 480px (i.e. an iPhone).

Things to remember

There are a few key things to remember when developing CSS for the iPhone:

  • Avoid explicit absolute widths—where possible you should use percentage widths.
  • Linearise everything—where possible, remove all floats. We want no content side-by-side unnecessarily.

The first thing to do is to set the -webkit proprietary CSS -webkit-text-size-adjust on the body which will resize the text for you, meaning you shouldn’t have to touch any font sizes yourself. Also, if your body copy is set in a sans font such as Arial, now is your chance to use some Helvetica—for normal sites, Helvetica should not be used as body copy as it renders hideously on a PC. Take advantage of the fact that you can guarantee its presence and quality on an iPhone. Change your font-family:

/*--- Main CSS here ---*/

/*------------------------------------*\
	IPHONE
\*------------------------------------*/
@media screen and (max-device-width: 480px){
body{
  -webkit-text-size-adjust:none;
  font-family:Helvetica, Arial, Verdana, sans-serif;
  padding:5px;
}
}

Above, I also added a small padding to make sure nothing touches the edge of the browser. All wrapper and content divs from here on in should be set to width:100%; making them the whole width of the screen, minus 10px.

Structure

Now, as all layouts differ I am going to assume a similar one to mine, a simple two column set up with a logo and menu in the header. If your layout is different I am sure you can quite easily retrofit it. As I mentioned before, remove all stylistic floats and set all widths to 100%. If you are using divs sensibly (i.e. for large bodies of content and not for nav items) this code should see you right for linearising the content:

@media screen and (max-device-width: 480px){
body{...}
div{
  clear:both!important;
  display:block!important;
  width:100%!important;
  float:none!important;
  margin:0!important;
  padding:0!important;
}
}

That will force all divs to rest one on top of the other, full width and in order. You have begun linearising all your content.

The navigation

If you have a navigation menu in which all the items are floated and made horizontal, insert the following:

@media screen and (max-device-width: 480px){
body{...}
div{...}
#nav,#nav li{
  float:none!important;
  clear:both!important;
  margin:0 0 20px 0!important;
  display:block;
  padding:0;
  text-align:left!important;
  width:100%;
}
#nav{
  border:1px solid #ccc;
  padding:5px;
  -webkit-border-radius:5px;
}
#nav li{
  margin:0!important;
}
#nav li a{
  display:block;
}
}

A screenshot of the CSS Wizardry navigation menu on an iPhone

This then will give you a vertical navigation menu which has a 100% width and the actual links themselves have a larger hit area (applied via display:block;), meaning that it’s prominent at the top of each page and easier for users to select single items.

Images

As images inherently have a set pixel width (i.e. their own width) there is a high chance that they will break out of the wrapper area (as a lot of images will be above 480px wide). To combat this simply add the following:

@media screen and (max-device-width: 480px){
body{...}
div{...}
#nav,#nav li{...}
img{
  max-width:100%;
  height:auto;
}
}

Other than elements very specific to my site, that is pretty much all the CSS I use to quickly size and linearise my content. Any elements specific to your own site will obviously need considering on a case-by-case basis, but if you remember to not set absolute widths and to always linearise your content then it should be a doddle. Oh and it’s a great time to use some guaranteed CSS3.

View a screenshot of an entire page of CSS Wizardry on an iPhone.

Do you have an iPhone version of your site? Have you any more tips you’d like to add? Please do so in the comments below.

+

Sunday, January 31st, 2010 in Web Development.

39 Responses to ‘iPhone CSS—tips for building iPhone websites’


  1. Apple Ipad Announced Today | Arrivals and Departures – Jon Van … said on 31 January, 2010 at 8:58 pm

    [...] iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … [...]


  2. Jim Moran said on 31 January, 2010 at 9:00 pm

    Nice article Harry, and what follows is more of a comment on our industry as opposed to these tips, for which I apologise.

    As a recent iPhone convert, and a much longer Nokia N73 sufferer, I was always annoyed that developers put their time into making CSS for the iPhone (which has a browser and UI capable of dealing with “regular” CSS) as opposed to the Nokia (terrible native browser or Opera Mini). I am sure modern Nokias are much better, but it still irks me a bit.

    Funnily enough, the mobile Twitter and BBC sites look terrible on the iPhone, but looked/worked great (as great as things work on 3G) on the N73. The BBC site even defaults to mobile version (as opposed to just different CSS) on the iPhone with no way of defaulting to the “desktop” version.

    I’m digressing a little but I think my point is to all the client side developers out there; there’s more to the mobile web than just iPhones.

    Anyone got any stats on mobile browsers?

    Jim.


  3. iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … | Iphone 3g Wizard said on 31 January, 2010 at 9:54 pm

    [...] Read the original post: iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … [...]


  4. Iphone 3G 2010 | iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … said on 31 January, 2010 at 11:42 pm

    [...] here to see the original: iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … [...]


  5. News Alert » Blog Archive » iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … said on 31 January, 2010 at 11:47 pm

    [...] post: iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … Tags: easiest, far-one, mobile, mobile-safari, one-resolution, only-ever, runs-on-webkit, [...]


  6. iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … | Coder Online said on 1 February, 2010 at 12:16 am

    [...] Continued here: iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … [...]


  7. iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … | I AM OSX said on 1 February, 2010 at 3:35 am

    [...] Excerpt from: iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … [...]


  8. iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … said on 1 February, 2010 at 5:32 am

    [...] the whole story here: Harry Roberts aggregated by [...]


  9. uberVU - social comments said on 1 February, 2010 at 8:06 am

    Social comments and analytics for this post…

    This post was mentioned on Twitter by CreativityDen: iPhone CSS – tips for building iPhone websites http://bit.ly/bDAFFW…


  10. Building Your Own Frames Tutorial | Picture Frames Express said on 1 February, 2010 at 2:43 pm

    [...] iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS … [...]


  11. iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS, Web Standards, Typography, and Grids by Harry Roberts : Popular Links : eConsultant said on 1 February, 2010 at 2:50 pm

    [...] more: iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS, Web Standards, Typography, an… 31 January 2010 | Uncategorized | Trackback | del.icio.us | Stumble it! | View Count : 0 Next [...]


  12. iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS, Web Standar… « Raghu-Net said on 1 February, 2010 at 3:20 pm

    [...] iPhone CSS—tips for building iPhone websites — CSS Wizardry—CSS, Web Standards, Ty… via Delicious popular by Jonnotie on 1/31/10 [...]


  13. CSS Brigit | iPhone CSS—tips for building iPhone websites said on 1 February, 2010 at 3:43 pm

    iPhone CSS—tips for building iPhone websites…

    An article covering the basics of designing and developing websites optimised for the iPhone.


  14. Bobby Marko said on 1 February, 2010 at 8:26 pm

    The user agent for the iPod Touch doesn’t have the string “iPhone” in it so using this method of detection won’t work for the iPod Touch. You should check for either iPhone or iPod or just check for the words “mobile” and “safari”.


  15. Jon said on 1 February, 2010 at 8:49 pm

    This is a great article and something I’ve been meaning to research. Curious as to how you would handle Android or other platforms as far as detecting it and styling for it?


  16. J Perry said on 1 February, 2010 at 10:40 pm

    Awesome! Just awesome :)


  17. Jonathan Foucher said on 2 February, 2010 at 8:06 am

    The advantadge of serving a different subdomain altogether to mobile devices, is that you can optimize the size of the markup, images, etc… making for faster viewing on a mobile device through 3G.

    If you need proof, try loading the normal version os say facebook on your mobile device, and then try the mobile version. There is a world of difference that could not be achieved using only CSS.


  18. MaFt said on 2 February, 2010 at 1:18 pm

    You can also use the following javascript to automatically ’scroll’ the site to shift the address bar out of view on load. As used at http://FindStuffNear.me – simply replace ‘wrapper’ with the required div name.

    window.addEventListener(”load”, function() { setTimeout(loaded, 100) }, false);

    function loaded() {
    document.getElementById(”wrapper”).style.visibility = “visible”;
    window.scrollTo(0, 1); // pan to the bottom, hides the location bar
    }


  19. Jake said on 3 February, 2010 at 11:31 pm

    Is there a way to give an option to to view full web page with this method?


  20. designi1 said on 4 February, 2010 at 12:33 am

    hey Hanrry,

    i wrote an article as well about this subject at designi1.com… is not so technical but i talk about the same problematic.. you might want to take look! :D

    there are some tools as validation web pages that can be useful when you´re developing this kind of stuff. Well i ill take a look more careful when i develop this feature at work! for now its saved :D


  21. Leko said on 8 February, 2010 at 7:27 am

    wow, awesome post man!! thanks to share!!


  22. dryan said on 8 February, 2010 at 7:33 am

    Jim, the last time I looked up the numbers (last summer), the Webkit-based browsers were about 85% of the mobile market. (See my slides at http://www.slideshare.net/danielryan/css-for-mobile.)

    For me, the effort to write for and test for that other 15% just doesn’t justify the time or my clients’ money. That said, I think the approach to sniff only for iPhone or iPod Touch leaves out the WebOS, Android and eventually Blackberry users that can handle the same content. If you’re going to sniff, I’d suggest searching for Webkit and mobile as your terms.


  23. dryan said on 8 February, 2010 at 7:36 am

    Oh I forgot to mention, Apple’s developer docs for Safari not only outline what CSS and JavaScript features are available, but the Human Interface Guidelines for webapps give some sensible defaults for type size and layouts. For instance, clickable targets should be at least 40×40 to avoid accidentally clicking the wrong element.


  24. Deavy said on 8 February, 2010 at 7:40 am

    To check the $browser in the detection code is enough to use:

    if ($browser) {
    /* do something */
    }


  25. Dominik Hahn said on 8 February, 2010 at 10:41 am

    Try this. :-)

    if (in_array($_SERVER['HTTP_USER_AGENT'], array('iphone', 'ipod'))) {
    echo 'Do something :-)';
    }


  26. RaphaelDDL said on 8 February, 2010 at 11:51 am

    Nice post.
    My studies demonstrate me that iPhone can’t handle very well body with margin:0;

    I made a page with a link #bottom and in the footer, a #top link. The bottom worked but top never worked. Then, i’ve removed one setting per setting and saw that margin:0; was blocking the anchor. Don’t ask me why, i don’t know.

    So, i’ve added just as experiment body { margin:0.1em;} and it worked. I’m still trying to understand why iPhone have this bug :/


  27. Maximilian Schmidt said on 26 February, 2010 at 5:50 pm

    Just used your tips for styling my website – very usefull!


  28. Gordon Tatler said on 28 February, 2010 at 5:38 pm

    Lovely, except that when this page is viewed on an iPod Touch some of your code snippets (on yellow background) run off the right hand side and are unreadable. Is this because you are only testing for iPhone and not both iPhone and iPod?


  29. Gabriel Silva said on 1 March, 2010 at 2:15 am

    Just found this WP Plugin for mobile devices visualisation:
    http://www.bravenewcode.com/products/wptouch/

    I haven’t tested yet but it seems to work pretty good. Might be helpful.


  30. 10+ useful code snippets to develop iPhone friendly websites said on 1 March, 2010 at 3:30 pm

    [...] CSS file.@media screen and (max-device-width: 480px){ /* All iPhone only CSS goes here */ }Source: http://csswizardry.com/2010/01/iphone-css-tips-for-building-iphone-websites/Automatically re-size images for iPhonesOn recent websites, most images are above 480 pixels wide. [...]


  31. Al said on 30 March, 2010 at 7:01 pm

    Thank you for your article, as it helped me create a mobile site for my iPod Touch. The top and bottom margins were always present no matter what I did to get rid of them, so I put my header as an image in tthe background rather than a real header, making the site look much better.

    http://egoinc.netai.net/mHome.htm


  32. Josh said on 13 April, 2010 at 5:19 pm

    Any tips for clearing CSS from an iPod Touch? The CSS seems to be solidly cached–clearing Safari history, cookies, and cache has no effect, even after force-quitting Safari and restarting the iTouch.


  33. Jimmy said on 26 April, 2010 at 12:08 am

    Great article. I am about to help a client set up his website on iphone and I will keep this in mind. Any suggestions on how to handle movies on the iphone. I know the IPOD doesn’t take flash so I am wondering what the best options are.


  34. Pietro said on 12 May, 2010 at 3:09 am

    I’m having troubles getting my iPhone to display correctly pages that use the “position:fixed” property. Do you guys have any suggestion, or are you aware of any known issue related to what I’m experiencing?
    Thanks


  35. Harry Roberts said on 12 May, 2010 at 1:54 pm

    Pietro,
    As far as I know there is no way of getting position:fixed; to work in Mobile Safari… This Stack Overflow article may be of some use though: http://stackoverflow.com/questions/743123/fixed-positioning-in-mobilesafari

    Harry


  36. Pietro said on 12 May, 2010 at 9:46 pm

    If you read my comment and are in my same situation, then read here http://cubiq.org/scrolling-div-on-iphone-ipod-touch/5#how-to-use-the-script Apparently this works.


  37. Lemonrock Editor said on 19 May, 2010 at 1:47 pm

    Your code for browser checking should be:

    <?php
    if (strpos($_SERVER['HTTP_USER_AGENT'], “iPhone”) !== false) {
    $isIphone = true;
    }
    else {
    $isIphone = false;
    }

    if ($isIphone) {
    (… iPhone specific code…)
    }
    ?>

    strpos returns either a positive integer ( >= 0) or, if the string is not found, false. See:

    http://php.net/manual/en/function.strpos.php


  38. Victor Reyes said on 27 May, 2010 at 9:24 pm

    Thanks for the tips. How do i create a “view full site” link without the iphone redirecting me to the mobile site again?


Leave a Reply

Respond to iPhone CSS—tips for building iPhone websites
Search CSS Wizardry

Archives

Categories

Twitter—2089 followers

You should follow me.

Subscribe—RSS