CSS, Tutorials

How to use hi-res images in web apps for iPhone4

If you have been developing websites and web apps for mobile, you may have noticed that the images are not very crisp on iPhone 4. The Retina display on iPhone 4 is the sharpest, most vibrant, highest-resolution phone screen ever but you need to know how to utilise it. The images you use on the websites need to be high resolution (at least 2 times bigger than the normal size) in order for them to look sharp on iPhone 4. The good news is, it is possible to use hi-res images in web apps / websites for iPhone4 without using any javascript.

For images that are displayed via <img> tags:

Save the image in x2 resolution. For example, if your logo is 50×50 pixels, make sure it is saved as 100×100 pixels (Resolution: 144 in Photoshop)

And in your HTML source code, make sure to specify height and width attributes for the <img> tag like below:

<img src="images/logo.png" alt="Web Development Blog" width="50" height="50" />

For images that are displayed as background images via CSS:

This is a bit trickier, because you don’t want to use hi-res images for iPhone 3 or Android or other mobile browsers. To target just iPhone 4, add the following line of code in the <head> section of your page right after the normal CSS include.

<link rel="stylesheet" href="css/common.css" />

<link rel="stylesheet" href="css/hires.css" media="only screen and (-webkit-min-device-pixel-ratio: 2)"/>

And for every image, you need to save 2 versions – one for the regular view and the other one for the hi-res view. For example, button-signup.jpg and button-signup2x.jpg. The button-signup.jpg will be 50×20 pixels whereas the button-signup2x.jpg will be 100×40 pixels.

In your hires.css file, you will have something like the following:

#signup { background: transparent url(../images/button-signup2x.jpg) 0 0 no-repeat; background-size: 50px 20px; }

Note that the background-size is the size of the image in regular view. This will allow the background image to be shrunk so it fits within the specified element. The background-size property is a CSS3 property and it lets you specify the size of background images.

And in your style.css, you will have:

#signup { background: transparent url(../images/button-signup.jpg) 0 0 no-repeat; }

And that’s all!

Career Guide for Software Developers