Today I'm going to show you how to build an alternate page and style sheet for the iPhone and iTouch. We will cover how to detect if the user is using an iPhone to view your page as well as the orientation of the device - whether it be landscape or portrait. To accomplish this we will be using javascript, and some Safari mobile specific CSS tags.
Getting Started
We're going to start off with 2 psd's I made and get those working in an iPhone page. I am using images for the background and header although you could use just straight colors instead of images. The plus side to not using images is that it obviously loads faster but also when switching between landscape and portrait the images take a moment to load, depending on how large they are. You can find the source psd files here or you can make your own. Something to keep in mind is that we are building a page specifically for the iPhone or iTouch. If you do not have the device yourself you can download the iPhone SDK freely from Apple and it includes an iPhone simulator. if you would like to detect the iPhone on your standard browser page and either load the iPhone css and html through conditional statements or send the user to a different page entirely, use the following code:

<script type="text/javascript">
var browser=navigator.userAgent.toLowerCase();
var users_browser = ((browser.indexOf('iPhone')!=-1);
if (users_browser)
{
document.location.href='www.yourdomain.com/iphone_index.html';
}
</script>
The code above explained:
- Line 2: Create a variable that holds the users type of browser ( among other things )
- Line 3: Assign the browser type a value if the iPhone browser is present.
- Line 4 - 8: An if statement that redirects the user to an "iPhone formated page" if the variable "users_browser" returns a value ( meaning the user is using an iPhone or iTouch to view the current page ).
Below the code will use html conditional statements to hide the code from a regular browser.
<!--#if expr="(${HTTP_USER_AGENT} = /iPhone/)"-->
<!--
place iPhone code in here
-->
<!--#else -->
<!--
place standard code to be used by non iphone browser.
-->
<!--#endif -->
Step 1: The HTML
So we now know how to point the user to your iPhone page if they are on an iPhone or iTouch device. Now, we will start working on the iPhone HTML page; the code below has some key differences from a regular XHTML transitional document.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"> <title>My iPhone Page</title> <link rel="apple-touch-icon" href="images/myiphone_ico.png"/> <link rel="StyleSheet" href="css/iphone_portrait.css" type="text/css" media="screen" id="orient_css">
The code above explained line by line:
- Line 1 - 5: This is standard 1.0 XHTML Transitional Doctype. Nothing special yet.
- Line 6: This line is iPhone and iTouch specific. It sets initial values for the viewport in the Device's browser. width=device-width states the width of the page to be the same width of the device. initial-scale and maximum scale set the starting point for the zoom of the page, maximum-scale is how much the page cane be scaled up.
- Line 9: This link element is pointing to the web pages icon. this is used when a user saves the page to their "Home Screen".
- Line 10: A link element points to the iPhone style sheet. This element has the id orient_css assigned to it. This is so that we can point to it with javascript to change the css file it points to when it comes to adjusting the layout for the orientation of the device.
Step 2: Laying Out The Divs
We now continue with the rest of the html before we add any javascript functions for orientation detection. Start with ending the head and then start the body. In the body element we add onorientationchange=orient();. So I just lied, that is a bit of javascript, but this is needed to call our "orient" function (we'll go over this in a bit) when ever the device detects a different orientation.
</head> <body onorientationchange="orient();"> <div id="wrap"> <div id="header"> </div> <div id="content"> <p>This is the main content area of the page. </p> <p>Using css and javascript we can manipulate any of these divs using an alternate css file. The css files in this project are for landscape and portrait views.</p> <p>Some more filler text here to demonstrate the page.</p> </div> <div id="bottom"> </div> </div> </body> </html>
Step 3: The Orientation Javascript
In the head of the page you will want to place the code seen below
<script type="text/javascript">
function orient()
{
switch(window.orientation){
case 0: document.getElementById("orient_css").href = "css/iphone_portrait.css";
break;
case -90: document.getElementById("orient_css").href = "css/iphone_landscape.css";
break;
case 90: document.getElementById("orient_css").href = "css/iphone_landscape.css";
break;
}
}
window.onload = orient();
</script>
switch(window.orientation) works off of the onorientationchange() method in the body element. This will check to see if the current rotation is equal to the "case value", if it returns true it will execute what is after the colon. After an orientation has been matched it breaks out of orient();. window.onload() runs the orient function when the page first finishes loading.
After each case (value) : we have javascript pointing to the link elements id that our css file is attached to. Depending on the case value, 0, 90 or -90 ( there is also 180 but it is not supported on the iPhone at this time) the portrait or landscape css file is attached to the href tag in the link element. 0 is upright (portrait), 90 is landscape counter clockwise. -90 is landscape turned clockwise and 180 although not supported yet would represent the device being upside down.
Step 4: Implementing The CSS
Even with all of this code, the page doesn't do much. That's because we need to add background images and style it all. We will create 2 css files, one called iphone_portrait.css and another called iphone_landscape.css. We will place the portrait css file into the link element as the default css file to use.
body
{
background-color:#333;
margin-top:-0px;
margin-left:-0px;
}
#wrap
{
overflow:auto;
width:320px;
height:480px;
}
#header
{
background:url(../images/header.jpg);
background-repeat:no-repeat;
height:149px;
}
#content
{
background:url(../images/middle.jpg);
background-repeat:repeat-y;
margin-top:-5px;
}
p
{
margin:5px;
padding-left:25px;
width:270px;
font-size:10px;
font-family:arial,"san serif";
}
#bottom
{
background:url(../images/bottom_corners.jpg);
background-repeat:no-repeat;
height:31px;
margin-top:-5px;
}
The above code is for the iphone_portrait.css file and is rather straight forward. Some things to note are:
- in the wrap style description overflow:auto makes sure floated items are kept inside the wrap div to keep the page nice and tidy.
- the dimensions for the page are 320px wide by 480px tall. be sure to state this in the wrap div.
Below is the code to be placed inside the iphone_landscape.css file. the only differences between portrait and landscape css files are the background images, the wrap dimensions are reversed and the margins are adjusted accordingly.
body
{
background-color:#333;
margin-top:-0px;
margin-left:-0px;
}
#wrap
{
overflow:auto;
width:480px;
height:320px;
}
#header
{
background:url(../images/l_header.jpg);
background-repeat:no-repeat;
height:120px;
}
#content
{
background:url(../images/l_middle.jpg);
background-repeat:repeat-y;
margin-top:-5px;
}
p
{
margin:5px;
padding-left:25px;
width:370px;
font-size:10px;
font-family:arial,"san serif";
}
#bottom
{
background:url(../images/l_bottom_corners.jpg);
background-repeat:no-repeat;
height:37px;
margin-top:-5px;
}
If you are using my sliced background images your page should now look like the image below when in portrait mode.

Or, in landscape mode?

Where To Go From Here?
So now that you have a page formatted and styled for the iPhone and iTouch, what else can you do? Well, if your page is meant to be more of a web app you may want to check out the IUI by Joe Hewitt which is a framework that makes your pages look like native iPhone or iTouch apps. Also keep in mind that you can set 3 specific css files; so you can have one css file that styles the page if its turned clockwise to landscape and a different file again for when its turned counter clockwise to landscape. This will allow for some interesting outcomes. Good luck!
Related Posts
Check out some more great tutorials and articles that you might like
Plus Members
Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.












User Comments
( ADD YOURS )Bjorgvin Gudmundsson August 18th
Thanks, im sure I can use that for something.
( )Jeroen August 18th
How to detect ipod touch?
( )Steven August 18th
I would love to see an article about creating iPhone compatible sites that contain video.
( )Brandon Burke August 18th
Very nice. I was just about to fumble through this myself.
( )Michael Castilla August 18th
Great tutorial! Thanks for sharing. Is there a demo page where we can test this?
( )Taylor Satula August 18th
This detect is a god sent. I have been looking all over the interwebs for this and it was served to me on a silver platter right when i was going to give up.!!!
Thanks NETTUTS
( )Taylor Satula August 18th
Huh i forgot that you can use tags on wp…
Duh.
( )Richard Neary August 18th
@Jeroen the iPhone and iPod Touch use the same OS so this will apply for both devices.
( )Craigsnedeker August 18th
Thanks a lot for this! IF someone has an iPhone and I make a page using this tutorial, could you send me a picture of your iPhone with my site on it? (I don’t have one, and probably won’t get one)
( )'web designer' Kathaperumal August 18th
Thanks for this sharing. useful article. As a web designer and owner of a web development company, this article used to upgrade my knowledge. Thanks lot
( )by
pkp
Ben Griffiths August 18th
Really good intro - I’ve been interested in this for a while, seems like now’s a good time as any to start
( )VertigoSFX August 18th
This is fantastic…it’s a great service to offer if you’re a freelance designer/developer to say that you can create iPhone compatible websites (and others for that matter). Great tutorial!
( )aaron August 18th
What’s the DPI in PSD for iPhone? I thought it was 150 DPI? Please verify. Thanks!
( )w1sh August 18th
Good tut, actually helpful and I hate to say this, but I’m obligated by my fans to say:
“Thaaaaannnnnkk God!!!! Yet ANOTHER cell phone tut! And here I thought you guys had given up on us after we didn’t learn how to make the world revolve around cellphones after the initial infinite tuts!!”
( )Bryan Grajales August 18th
I think I love it ajajaja, Nice tutorial… First time i seen a tutorial for iphone and itouch!
( )Christian Mejia August 18th
I love Nettuts. I really do love Nettuts and the Envato family. Thank you for making my day!
( )Braden Keith August 18th
Ahhhhh THANKS!
( )More of these!
James August 18th
Bookmarked for the future… I’m not normally in favor of user agent string sniffing but this seems to be a valid way of using it…
To be honest though, we, as web developers should never have to cater for a specific device. It’s against web standards and plain logic for us to recode websites just to suit new technology and gadget trends! I doubt I’ll put much effort into doing this - Is it really time-well-spent??
( )Taylor Satula August 18th
The iPhone And touch have seperate useragents though. It doesn’t detect my touch. …You could roll the iphone and touch js redirect files into one and point them both at the same place
( )Dan August 18th
Great tut. First one I’ve seen that addresses the horizontal display mode for your website! Finally! Thanks
( )Neil August 18th
Dan, RC did a tutorial for the iphone a few weeks ago on Layers Magazine TV. Great tutorial non the less
( )ethayne August 18th
Yeah! I want my website to change colors when I view it in landscape! Haha, great article, I was thinking about doing this.
( )insic August 18th
Holy COW! i really like this article you got here. i am having a mobile project just this week. and darn it is useful.
( )Dpm Joly August 19th
In javascript:
if ((navigator.userAgent.indexOf(’iPhone’) != -1 ) || (navigator.userAgent.indexOf(’iPod’) != -1)) {
( )Shane August 19th
For those interested in more information, you can check out http://developer.apple.com/iphone/.
Thanks for the tutorial.
( )Barry August 19th
I am a developer for the iPhone, i make rich apps on the iphone. I have a server side solution for to detect the iphone. Maybe i will post some of my stuff in here.
( )Lamin Barrow August 19th
Interesting tut. It is a deviation from the stream of Wordpress tuts we had in the last little while. Thanks for all of your time and effort.
( )MGK August 19th
Nice thingy but i would have made it in php (so that it would work even if the visitor have disabled js).
It would look like that :
( )MGK August 19th
ouch, forgot that the php code is disabled in comment
ok
so again :
if (ereg(”iPod|iPhone|Aspen”, $_SERVER["HTTP_USER_AGENT"]))
{
echo ‘iphone/itouch/aspen’;
}
else
{
echo ‘not iphone/itouch/aspen’;
}
aspen is the name of the emulator of the iphone, with the sdk of apple
( )Patrick August 20th
Nice and usefull tutorial. Tks lot.
@MGK: Tks for the tips: php user agent works fine.
( )Anders Ringqvist August 20th
Can you please explain the 2nd code listing? You say it´s “html conditional statements”. That is something I never heard of. I read about “MSIE html conditional comments” but the syntax is different. Can you please point me to some reference or demo where I can see these “html conditional statements” in action? It´s not included in the source_files.zip that you link to at the beginning of the article. Further you say “You can find the source psd files here or…” but there are no photoshop files included in that package.
( )John August 20th
Great article! I tried adding content dynamically using PHP/MySQL but it didn’t work. Before I get myself all crazy troubleshooting, does anything special have to be enabled to do this?
Thank you again for all of your hard work.
-John
( )James Black August 20th
@Anders Ringqvist
You will find the zip file containing the psd files for the portrait and landscape view of the page by clicking on my name to the left of this comment. As for the html conditional statements, they are widely used for Internet Explorer, but generally work for any type of conditional statement. In this case we are using html to check if the browser is the iphone browser.
A basic HTML conditional statement looks like this
This is typically not that very best way to do this though. Personally I would probably use php as MGK described above. I simply showed you a few different ways to accomplish this which are pretty simple. Hope that helps!
( )slith August 20th
whats the difference with developing for iphone or ipod touch? just curious because i’m interested in developing apps however i dont want to switch my phone provider just to get the iphone. i figured the ipod touch would allow me to browse and develop iphone type apps.
( )John August 20th
had bad path - includes PHP np. Thanks again
( )Taylor Satula August 21st
usually i just do a alt stylesheet for iphone and that works just fine for me. But thats just my opinion
( )Rob Fletcher August 22nd
I’m a coldfusion programmer, so here is how i would detect the iPhone, iPod in Coldfusion.
You are viewing this page with an iPod Touch or other iPod device.
You are viewing this page with an iPhone.
You are viewing this page a PC/MAC.
The sometext could easily be changed to something like a cflocation to redirect users to a special iPhone page. the #CGI.HTTP_USER_AGENT# is the built variable to get the user agent of the browser. I have tested this code on an iPhone and iPod touch.
Enjoy.
( )Rob Fletcher August 22nd
oops — code got removed:
( )cfif #CGI.HTTP_USER_AGENT# CONTAINS "iPod">
You are viewing this page with an iPod Touch or other iPod device.
cfelseif #CGI.HTTP_USER_AGENT# CONTAINS "iPhone">
You are viewing this page with an iPhone.
cfelse>
You are viewing this page a PC/MAC.
/cfif>
Jay Salvat August 25th
Hi, good topic for a Tuturial.
Here is an alternative approach to switching between to separate Css files. It just adds a new ‘orient’ attribute to the Body tag. In your function orient():
function orient() { switch(window.orientation) {
case 0:
orient = “portrait”;
break;
case -90:
orient = “landscape”;
break;
case 90:
orient = “landscape”;
break;
case 180:
orient = “portrait”;
break;
}
document.body.setAttribute(”orient”, orient);
}
So you can use the Css that way:
body[orient="portrait"] {
background:#FF0000;
}
body[orient="landscape"] {
background:#000;
}
Also, the iPhone built-in Safari browser works with webkit. You can use the border-width and -webkit-border-image combo to stretch the middle part of an image and keep the left and right side intact.
Example in your code:
#content {
border-width: 0 25px 0 25px;
-webkit-border-image: url(middle.jpg) 0 15 0 25;
}
#bottom {
border-width: 10px 25px 0 25px;
-webkit-border-image: url(bottom_corners.jpg) 0 25 0 25;
height:31px; }
So you don’t have to maintain two sets of images/css files for ‘Portrait’ of ‘Landscape’ mode.
Ok webkit things and ‘orient’ attributes added to the Body are not web standard approaches, but we are talking about iPhone here, no really need of accessibility
Last point, your browser detection doesn’t take care about iPod touch which provides a different User Agent. Something like that should detect an iPod Touch properly:
Chapter Getting Started, Line 03:
var users_browser = ( browser.indexOf(’iPhone’)!=-1 || browser.indexOf(’iPod’)!=-1 );
Regards,
( )Jay
Endodontist August 25th
Thanks, great tutorial. Useful.
( )insic August 29th
posting a nightly or quick tips article on how to detect different type of mobile / mobile browser would be a nice idea.
( )switch September 3rd
This is awesome dude! Thanks! Will definitely be using this sometime!
( )cchana September 3rd
great tutorial. i’m looking to get an ipod touch soon, so i’ll be looking to make good use of something like this. might come in handy for future web app building too!
( )Benjamin David September 12th
Thanks a lot ! I didn’t know where to start and it really helped.
( )Jonno Riekwel September 17th
Nice tutotial, if it worked. I’m a experienced webdesigner/coder for a few years now and I did everything you wrote, but guess what, it doesn’t work at all.
Why don’t you offer a downloadable example?
( )stefan September 21st
im not having any luck with this, and why isn’t there an demo? any help would be great.
( )Ricco831 September 23rd
This is an awesome tutorial. I have been looking for a tutorial like this for the longest time. I actually found this site on http://www.iphonedevver.com which is an iPhone SDK tutorial search site.
( )Brian September 24th
These two lines contradict each other:
# var browser=navigator.userAgent.toLowerCase();
# var users_browser = ((browser.indexOf(’iPhone’)!=-1);
It should either be
# var browser=navigator.userAgent.toLowerCase();
# var users_browser = ((browser.indexOf(’iphone’)!=-1);
or
# var browser=navigator.userAgent;
# var users_browser = ((browser.indexOf(’iPhone’)!=-1);
This is because the indexOf() statement IS case sensitive.
( )Erika September 26th
Why not just use a CSS media type to send iPhone to its special stylesheet?
( )illastricz October 2nd
I’m sorry I dont get it working, where doo you have to put this script???
I tried lots of things but it doesn’t work:S and is this java or some other type of script??
( )illastricz October 2nd
srry this script:
# <!–#if expr="(${HTTP_USER_AGENT} = /iPhone/)"–>
( )#
# <!–
# place iPhone code in here
# –>
#
# <!–#else –>
#
# <!–
# place standard code to be used by non iphone browser.
# –>
# <!–#endif –>
iphone forum October 7th
Got a question about the iPhone? Ask away. Think you can Answer any question about the iPhone?? Lets see. http://www.iPhoneAnswers.org
( )Anthony Hand October 21st
Thanks for this article! I’m actually just getting into iPhone-optimized web site design more deeply and this article is very useful.
I wrote some very lightweight JavaScript and PHP code for web site owners to detect mobile devices. The code is available for free download!
- JavaScript: http://www.hand-interactive.com/resources/detect-mobile-javascript.htm
- PHP Code: http://www.hand-interactive.com/resources/detect-mobile-php.htm
Download the code and follow the simple instructions. You can detect as broadly (Is this a smartphone class device?) or as narrowly (Is this an iPod Touch?) as you need.
So take a look at the code and see if it helps you better meet the needs of your web site visitors!
Cheers,
( )Anthony Hand
Mobile User Experience Designer
moumni October 25th
thanks dude, used your css with my home security/monitoring system. looks great on my iphone now
( )Busby November 1st
This articles is very useful! I have tried it on my Iphone and the site fits well!
( )vinoy January 21st
One can test thr sites on http://iphonetester.com/
( )Raphael January 23rd
Can you incorporate wordpress or some kind of blogging feature with this?
( )Douglas III April 8th
Wordpress has a FREE iPhone app so you’ll want to use that.
( )nikhitha c p February 10th
excellent!!
( )mymamakcorner February 28th
thanks , this is a very good tutorial.
( )Web Design Creatives March 15th
Thanks, It’s really nice informative post. I was looking for the same
( )iTod March 24th
This is great but how do you create sliding pages. or links to secondarypages?
( )Anton Ongsono April 22nd
how to detct touch for zoom in or zoom out?
( )iphone architect May 6th
great article, hanks
( )rzmota May 15th
thanks for this tutorial, but I am looking for a somthing which can load a new HTML document after rotate iphone, so it will work on the same idea as above but change the filepath not the css style document.
Anyone has an idea?
Thanks a lot.
( )mat May 27th
I have my page done, on the page is a link to call a phone #. This works fine unless you are on an iPod Touch. what code can I add to make a dialogue box pop up telling the user that they are on an iPod and not an iPhone? Here is what i have so far:
#
Thanks!
( )mat May 27th
that code didn’t take above-
#
( )FemaleEDPillz June 25th
Hello
Thank you for this website! Here is mine http://motrin.wikidot.com/
( )