Web Development for the iPhone: Targeting the iPhone Safari browser
Developing for the iPhone
Also check out Creating native looking iPhone web apps with CSS3 (no images). That works on the iPhone and Safari 5 only. Also see CSS, XHTML and JS support in the iPhone. It’s way more relevant than this article, which is about v1.
- The Safari iPhone user agent string is:
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+
(KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3 - Platform string:
(iPhone; U; CPU like Mac OS X; en
) - Version string:
Version/3.0 Mobile/1A543a Safari/419.3
To target the iPhone with CSS, use:
<!--[if !IE]>--> <link media="only screen and (max-device-width: 480px)" href="iPhone.css" type="text/css" rel="stylesheet" /> <!--<![endif]-->
The logic of this is that only browsers that understand screen
understand only
, and of these, only the iphone has a max-device-width
of 480px
. The reason for the anti-IE comments is that some versions of IE render CSS regadless of media type declarations.
To target the iPhone server-side with PHP you can use:
if (stripos($_SERVER['HTTP_USER_AGENT'], 'iPhone')) {}
:hover pseudoclass on the iPhone
Please see hover pseudoclass for the iPhone to learn how to simulate hover effects on the iphone
iPhone Viewport Orientation
The iPhone supports both landscape and portrait views. You can specify CSS based on viewport orientation which you determine via javascript and update the orient
attribute of the body
element. Target the browser with body[orient="landscape"]
or body[orient="portrait"]
iPhone ViewPort Orientation JavaScript
The following javascript snippet detects and sets the iPhone’s viewport orientation by evaluating the innerWidth
property of the window
object and setting the orient
attribute of the body
element at regular intervals:
var updateLayout = function() { if (window.innerWidth != currentWidth) { currentWidth = window.innerWidth; var orient = (currentWidth == 320) ? "profile" : "landscape"; document.body.setAttribute("orient", orient); window.scrollTo(0, 1); } }; iPhone.DomLoad(updateLayout); setInterval(updateLayout, 500);
Hiding the iPhone toolbar
With one line of JavaScript you can hide the big toolbar: window.scrollTo(0, 1);
. Include this line of code to your snippet of detecting the phone’s orientation, as the toolbar will reappear when the orientation is changed. Remove it from the snippet above if you want the toolbar to show.
iPhone Viewport Meta Tag
The viewport meta tag properties include width, height, initial-scale, user-scalable, minimum-scale and maximum-scale
. The height is calculated based on the width and aspect ratio. The initial-scale is the scale to render when the page first loads; with the default to fit the screen. Unless user scalable is set to no, th user can change the scale through pinching and double tapping of the iPhone.
Property | Default Value | Minimum Value | Maximum Value |
---|---|---|---|
width | 980 | 200 | 10000 |
height | based on aspect ratio | 223 | 10000 |
inital-scale | fit to screen | minimum-scale | maximum-scale |
user-scalable | yes | no | yes |
minimum-scale | 0.25 | > 0 | 10 |
maximum-scale | 1.6 | >0 | 10 |
Examples:
<meta name="viewport" content="initial-scale=2.3, user-scalable=no" /> <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
The iPhone automatically adjusts font size for readability. This feature can be overridden with -webkit-text-size-adjust
. The values for -webkit-text-size-adjust
are none (default) | auto | %value.
Note that if you have a web page designed for the desktop that is wider than 980px, you will always have scrolling on the iPhone. The solution? For example, if your the site is 1060px wide, iPhone’s Safari only scales up to 980px: this will cause a small amount of zooming. In this scenario, the simple fix of <meta name="viewport" content="width=1060" />
will fix it all.
Comparisons of Safari on the desktop versus the iPhone.
Safari on iPhone supports:
- Safari supports cookies on both
- Safari on iPhone allows up to 8 user initiated browser pages to be open at once.
- Default user preference is set to block pop-up windows.
- Safari on iPhone supports many MIME types and rich media, including PDF and media file types
- Images: Safari supports
.gif, .jpg, .png,
and.tiff
- Fonts: The iPhone comes with American Typewriter, Arial, Arial Rounded MT Bold, Courier, Courier New,Georgia, Helvetica, Helvetica New, Marker Felt, Times New Roman, Trebuchet MS, Verdana, and Zapfino; so that’s what Safari on the iPhone supports.
- Other than the :hover pseudoclass which isn’t supported on the iPhone since mouseover effects aren’t supported, Safari on the iPhone supports CSS1, CSS2 and several selectors and attributes of CSS3. If you do want to include a hover pseudo class, check out: hover pseudoclass for the iPhone.
Safari on iPhone does not support:
- Events:
mouseover
andmouseout
, including:hover
styles and tool tips, (but it does supportonclick
andevent listeners
). Safari on the iPhone does not support the document events of onkeydown, onkeypress and onkeyup, the form-field events of ondblclick, onmouseenter, onmouseleave, onmousemove, and onSelect, and the window events of onresize and onScroll. This is not an exhaustive list, so test your event handlers before listening to me. window.showModalDialog()
- Plug-ins: Flash or Java, and plug-in installations. Do not ask users to download Flash.
- File-size: Non-streaming files of over 10MB. CSS, JavaScript and HTML files are limited to 10MB per file. JavaScript is limited to 5 seconds of execution time. Safari for the iPhone does support gzip compression, so compress!
- The iPhone does not support gifs, png or tiffs over 8 MB and jpgs over 128 MB (but does support larger streaming media files).
- You can use iFrames, but avoid framesets.
Other iPhone Safari features
Phone numbers are automatically converted to phone links. You should convert them instead of letting Safari control it for you.
<a href="tel:4155551212">415.555.1212</a>
.
Notes:
- Check out the game we (Nicol, Greg and I) developed at iPhoneDevCamp2 – Tattle Talz (two truths and a lie) – http://tattletalz.com.
- Check out the application we (Ryan, Richard, Seto and I) developed at iPhoneDevCamp – PickleView – http://mxis.com/pickleview.
- I don’t own an iPhone. Feel free to send me one! 🙂
“You can specify CSS based on vieport orientation with the dynamically changed orient attribute which Safari for the iPhone adds dynamically to the body element. Target the browser with body[orient=”landscape”] or body[orient=”portrait”]”
Safari for the iPhone does not add this attribute. It is obtained using a JS hack. Example: http://www.iphonewebdev.com/examples/liquified/liquified.html
-Kalle.
Thanks Kalle. I updated the blog with a snippet from the Pickleview Code.
Check out Joe Hewitt’s iUI at http://www.joehewitt.com/iui/
Don’t forget to check out my blog post on CSS support on the iPhone. I tested all teh CSS1, CSS2 and CSS3 selectors on the iPhone and posted the results at http://www.evotech.net/blog/2007/07/safari-30-css-support/ .
If you want to compare the iPhone to web browsers, I ran the same tests on all Grade-A browsers and posted those at http://www.evotech.net/blog/2007/04/css-selectors-and-browser-support/
Thank you for the article. I will be referring to it alot.
I have a question… Has anyone seen any information on the pinch-in and pinch-out gestures? Does Safari trigger an event and if so any examples?
Thank you in advance.
-Al
The application i developed with Seto, Ryan and Richard is hilited on the Apple iPhone Webapp home page. Woohoo! Check out http://www.apple.com/iphone/webapps/ third from left!
Hi, I’m wondering what the line:
“iPhone.DomLoad(updateLayout);”
does in the ViewPort Orientation script. I can’t find any documentation on this anywhere… could you clarify/let me know where you got this from?
Thank
Ali
iPhone Web Developer Tool
http://www.manifestinteractive.com/iphone/
This application allows you to use your iPhone for Web Developing. You can View Source, Find on Page, Outline Divs & Tables, etc. Similar to the Firefox Web Developer Extension. Simply drag bookmarks into the web browser that you have your iPhone or iPod Touch synced to and you’re good to go. Works on any site.
Let me know what you think. If you have stuff you want added just let me know.
– Peter Schmalfeldt
When using window.scroll to hide the Safari tool bar, does the javascript need to be part of an onload event? Or can it just be inline javascript? -Tony
Truly Amazing and informative !
The iPhone application / game I developed with Nicole and Greg at iPhoneDevCamp2 won best game. Check it out at http://www.tattletalz.com
Note the body:first-of-type selector is a great way to target safari only. I go over that hack in my other blog post. Just wanted to re-mention it though, since i used it mercilessly in the last iPhone app i did, and it worked fabulously.
CSS :hover works if the element has onmouseover set, so I just set an onmouseover=”” on the element that I want the :hover to work on.
Estelle,
Is the code:
–>
<!–
… absolutely correct? Two reasons I ask:
1. the commenting characters seem wrong, shouldn’t it be:
2. On the iPhones I’ve checked this doesn’t apply the css, is this a version specificity?
Cheers for all your hard work on these snippets, I’ve added your site to my toolbox! 😀
Thank you for your time and patience,
J
By the way, the property formatting in your viewport meta tag is vital. Do it exactly as the blog post’s example displays it.
I had originally removed the spaces between the semi-colons and the property declarations. This made them ineffective.
CORRECT:
<meta name=”viewport” content=”width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;” />
INCORRECT:
<meta name=”viewport” content=”width=320;initial-scale=1.0;maximum-scale=1.0;user-scalable=0;” />
Thanks,
Ernest
http://iq.ifonify.com
hi There
Fantastic information. Thank you.
I’ve tried a simplified variation of your updateLayout script (without the orentation detcection) and it presents an irritating problem.
I can’t manually scroll to the tool bar.
Everytime I try to scroll, it seems that safari is reloading the page (the onLoad event is firing), and causes it to scroll back to the default position.
This makes it irritating/difficult for user to go to another page once they’ve finished with my site.
I would not have thought a user initiated scroll would cause the page to reload.
Can you shed any light on this?
function updateLayout() {
window.scrollTo(0, 1);}
if (navigator.userAgent.match(“iPhone”)) {
setInterval(updateLayout, 500);}
Hi Estelle,
Safari on iPhone does support :hover styles and tool tips (and probably onmouseover and onmouseout events).
To activate it: hold on a hyperlink for a while…
The tooltip and hyperlink-url will be displayed in a ‘balloon’ pop up and the :hover style will be applied to the hyperlinked content.
Hi Estelle,
It is true that iPhone supports :hover? I don’t have an iPhone so I can’t test. Does it support li:hover?
hi Guys,
iPhone does support :hover
i’ve tested a css based slideshow at
http://www.jampmark.com/web-scripting/pure-html-css-slideshow.html
using a new iPhone and it worked great!
Hi Practical Web Scripting-
I tested your page on my iphone, and the iPhone asks me if I want to save the image, but does not show the hover effect.
The best way to similulate the :hover effect in the iPhone that I’ve found is to add event listeners for the touchstart and touchend events. I wrote a quick article on this at http://www.evotech.net/blog/2008/12/hover-pseudoclass-for-the-iphone/
-Estelle Weyl
Server side browser sniffing? In 2009? Some things never change.
On thing that you may want to consider is writing your application using HTML, CSS, and JavaScript but making it installable. You could then use AJAX to connect this rich app to your server.
I wrote a framework that lets you do this without knowing any Objective-C. It does a lot such as:
– vibrate the phone
– get the GPS location
– give you access to the accelerometer data
– store data on the device with a wrapper to SQLite. This is both browser and non-browser based so you could ship data with your application if you choose.
– play system sounds
– record and playback audio files
– show and get the data from the native date and date/time pickers not just the one that is shown when the user selects an HTML pulldown
– Embed Google Maps in the application.
All of this is accessible from JavaScript calls and Bonjour Networking and service discovery is going to be in the next beta within a week.
Much more is planned for this framework so if you want to use your web skills and create installable iPhone applications this is something you should check out.
hi Estelle,
when you touch a thumbnail, the slideshow shows the bigger version of the image on the black area but when you tap on the bigger image, iphone would ask if you want to download the image or not.
But i’ll try the touchstart and touchend events.
thanks for sharing.
“if (stristr($_SERVER[‘HTTP_USER_AGENT’], ‘iPhone’)) {}”
THIS CLEARLY DOES NOT WORK.
The conditional comments in the css code above are not correct – don’t copy and paste them.
So @media only screen and (max-device-width: 480px) {
#wrapper {
margin: 0 20%;
}
}
works in Opera to.
I’m still looking for a css target for iphone..
Any idea how to get finger zoom events?
E.g. controlling some value (e.g. Map Zoom) via Fingers?
A couple of notes about device detection…
First. if you are making features that you want to work ONLY on iPhone OS devices, then consider that you don’t want to detect ONLY the iPhone. You want to detect both the iPhone and iPod Touch. So you would need to adjust your device detection algorithms.
I wrote a great PHP library for detecting mobile devices. (Also available in JavaScript, Java, and ASP.NET). The code is free, easy to modify, regularly updated, and available at:
http://www.hand-interactive.com/resources/
The second thing to consider is that if you’re going to go through all the trouble of creating an iPhone-optimized version of your site, then why not let it do triple duty on Android and Palm Pre (WebOS) devices, as well? These devices are also WebKit-based and iPhone optimized sites typically function equally as well on them. As a result, note in my code a simple API call for DetectTierIphone(), which will return a simple True or False for similarly-capable devices.
Happy designing!
Anthony
Pingback: Confluence: Team IT Development
Thank You!
It really helped me with the Iphone’s web-site constrution.
Does anyone knows if there exist som version of Safari you can install on a pc that works more like the iphone browser ?.
Textareas and richedit-textares might behaves differently as well on Iphone.
Pingback: Web Design for iPhone
Hey, does anyone know how to get a web app to only display on portrait, thus removing the ability to change Orientation. any help would be awesome thank you
Hi all,
Does anyone know if it is possible to configure a web page so that Safari selects the text in an input field when you “next” to it (like a normal browser selects the text when you tab to the field) or to automatically activate the number key pad when entering am input field?
Many thanks,
Chris
Hi ,
I m a beginner,I use testiphone.com to test my developing.I wanna remove the button bar that is toolbar at the bottom of iphone here.How can i do that?
Thanks
Dinesh
Excellent write-up, still valid today.
@chris-
Webkit supports the HTML5 input types. If you use input type=”tel” you’ll get a number pad, if you put type=”url” you’ll get the URL keyboard, etc. If you use the number type, you’ll get the number keypad.
Check out http://www.standardista.com/webkit/ch4/number.html for an example.
Next works for my on iphone.
Wow. You’ve put a lot of work into laying out all the details. Great post, I still have a few specific questions about developing for the iPhone, but I’m going to go back and check out some of the suggestions made by some commenting in the thread.
Is there a reason (besides trying to run my phone battery down) why you call updateLayout two times per second?
Why not use ?
Please read the Apple Safari Web Content Guide to see what I mean.
http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW16
BTW, as the Apple guide says, you can get the orientation from window.orientation
@Alfred
while I don’t think that will run down your battery too quickly, you’re right, it is no longer necessary. You can use media queries to determine orientation for changing the css based on orientation, or with js if you need to for js reasons.
This post was written in 2007, when the first iPhone first came out. Back then the media query for orientation was not supported. It is now. I think i included that in the slide show attached — which was done in 2010.
Thanks a lot , that is very helpful .
One should never use [if !iE] as a conditional comment. If there are “…some versions of IE render CSS regadless[sic] of media type…” then target those versions in your conditional comments. IE9 supports media queries. Use [if lt IE 9] instead. Windows Phones are getting IE9 in Fall 2011 with a screen resolution of 480px x 800px.
So @media only screen and (max-device-width: 480px) {
#wrapper {
margin: 0 20%;
}
}
works in Opera to.
I’m still looking for a css target for iphone..
Can we check iphone output on safari ?
Pingback: Cascading Style Sheets Reference Links | kabayview.com
Pingback: Detecting orientation changes in mobile Safari on iOS, and other supported browsers - Code Couch
Targeting specific browsers and platforms is not good web dev practice. We’re supposed to be using these things called “web standards”. Now we’re back in the 90s again… “if IE do this, if Netscape do this”.
Nice going. Good luck with that guys.
How can We create a floating toolbar for an iPhone/iPad apps?