If the first person to request an image is on a mobile phone, people who follow via the same CDN or cache will also see the mobile-optimized image even if they are on desktop unless consider CDNs in your strategy.
What is Screenfly?
Screenfly allows you to view your website on a variety of device screens and resolutions. Enter a URL and click on GO to get started.
About the Proxy Server
Screenfly uses a proxy server to mimic devices while you view your website. Want to try it out? Enter the address of a website, like Amazon.com, and see how you get an entirely different view on desktops, tablets, and mobile phones.
Having Trouble?
Screenfly doesn’t work on every website. Some websites don’t like to be displayed inside of frames, and others won’t work with the proxy server.
The Screenfly proxy server mimics the user agent string of the devices you select, but not the behavior of those devices. For example, most mobile phones and tablets have a zoom feature that displays the entire page at once, even if it appears to be clipped off the edges of the screen here. For best results, be sure to use the latest version of a modern web browser, such as Firefox, Safari, or Chrome.
A simple, useful and beautiful browser window resize app for Web designers and developers.
Smush.it uses optimization techniques specific to image format to remove unnecessary bytes from image files. It is a "lossless" tool, which means it optimizes the images without changing their look or visual quality. After Smush.it runs on a web page it reports how many bytes would be saved by optimizing the page's images and provides a downloadable zip file with the minimized image files. Do not link to the smushed images on Smushit.com since they will only be available there temporarily. Instead, download the zip file containing the smushed images for your web page and replace your image files with those files.Select the images you want to smushSelect the images you want to smushPaste image URLs here, one per line
I wrote yesterday about how the iPad3′s Retina display will cause issues for web designers. When the iPhone 4 came out, I can recall lots of fire drills at work to go through and update to Retina-ready graphics for a number of our clients. The iPad’s screen size compounds the problem.
“@Malarkey Screen resolutions are going to increase. Period. Adaptation is the name of the game in web design. The sky is not falling.” — @robweychert
The sky isn’t falling and adaptation is most-certainly the name of the game, but we do need better tools to deal with varied resolutions in order to better adapt. Apple will be releasing the equivalent of a car that can break the sound barrier, but is equipped with the same seat belts and airbags. Because this is right around the corner, it’s probably a good time to look at techniques to address these hi-res screens.
@media queries
We can use @media queries to target hi-res displays and serve them up different styles, including different background images. While not entirely related to images, Brad Birdsall demonstrates how you can finesse designs for hi-res displays. I wonder if there are the same issues regarding media queries and asset downloading with pixel-density as there are with device widths.
SVG
Several people mentioned how helpful SVG to be to create resolution-independent imagery. There’s a nice write-up on how to achieve resolution independence using SVG. Just make sure you check Max Firtman’s compatibility tables when implementing SVG. It’s still emerging.
@font-face
Using @font-face to create custom icons is a nifty trick. They’re crisp regardless of screen resolution. Chris Coyier has a great example of @font-face icons in action. Just make sure you’re only loading in the characters you need so you’re not serving up massive font files, which kind of defeats the purpose. Also check out Font Awesome, a free icon font made for use with Twitter Bootstrap.
Detect Network Speed
This is where things get tricky. Not all hi-res devices should necessarily get hi-res graphics. As I mentioned yesterday, a user might be on EDGE or 3G on a train or bus and might just want to get the content quickly, not have an immersive hi-res experience. The site’s performance and the user’s data plan takes a hit by getting served hi-res graphics by default. We need to be able to conditionally load assets/media based on how strong a user’s connection is.
navigator.connection looks like it can help, but basic types (EDGE, 3G, wi-fi, etc) don’t tell the whole story. A shared wi-fi network on a Bolt Bus or Starbucks can easily run slower than a 3G network.
There’s some other tools for detecting connection that look interesting. I’d love to hear if and how people are using them.
A new HTML element
The Responsive Image Working Group is trying to figure out how best to conditionally serve assets based on context. They’re proposing a new HTML element that takes device dimensions, network speed, pixel density and more into play in order to deliver contextualized web experiences. I’m excited to see what comes out of it.
Best Practices
- Start with the low-res graphic first- Many devices don’t have hi-res displays, so it would be foolish to serve them up massive hi-res images by default. Use detection to conditionally load in larger assets. This is similar to the mobile-first image approach for responsive designs
- Utilize basic image optimization principles – This is obvious, but take the time to optimize image assets, especially hi-res imagery, for mobile displays. Save for Web, optimize further, etc, etc.
- Use CSS3 techniques like background gradients, rounded corners, etc where possible to avoid using images altogether. I have a feeling there’s going to be a lot of (especially fashion) e-commerce websites that are going to feel the hurt once the iPad3 is released.
- Use resolution-independent solutions where possible- SVG, @font-face and even basic HTML special characters can help avoid issues with resolution.
- Detect network connectivity – This is on the horizon, but definitely keep it in mind as you’re creating your experiences.
- Be mindful of compatibility – There’s still many devices that don’t support SVG, @font-face and CSS3 techniques. Make sure to follow strong progressive enhancement practices to create an experience that supports more but is still optimized for these hi-res devices.
What else is missing?
A quick and easy grid calculator for pixel pros (and novices).
This is a list of selected devices’ displayed pixel density in pixels per cm (ppcm) (pixels per inch (PPI)). A display device has a limited number of pixels it can display, and a limited space over which to display them. On a small portable computer or cell phone, a higher pixel density is desirable, as these devices are designed to be viewed up close.
*Approximate calculation based on given display size.
*Approximate calculation based on given display size.
*Approximate calculation based on given display size.
**Device uses PenTile technology. Its pixels consist of only two sub-pixels instead of three and the claimed pixel density is only achieved using subpixel rendering. In any case, the ppi numbers are not directly comparable.
*Approximate calculation based on given display size.
**Device uses PenTile technology. Its pixels consist of only two sub-pixels instead of three and the claimed pixel density is only achieved using subpixel rendering. In any case, the ppi numbers are not directly comparable.
*Approximate calculation based on given display size.
*Approximate calculation based on given display size.
**Device uses PenTile technology. Its pixels consist of only two sub-pixels instead of three and the claimed pixel density is only achieved using subpixel rendering. In any case, the ppi numbers are not directly comparable.
*Approximate calculation based on given display size.
*Approximate calculation based on given display size.
Diagonal cm (in) Resolution Pixels Aspect ppcm (PPI) Details Width cm (in) Height cm (in) &100000000000000015000003.8 (1.5) &10000000000023232000000176×132 23232 4:3 &1000000000000014700000058 (147) media player display, Apple iPod Nano 1st & 2nd generation &100000000000000011999993.0 (1.2) &100000000000000009000002.3 (0.9) &100000000000000018000004.6 (1.8) &10000000000076800000000240×320 76800 3:4 &1000000000000022200000087 (222) phone display, Sony Ericsson W880i &100000000000000010800002.7 (1.08) &100000000000000014399993.7 (1.44) &100000000000000018999994.8 (1.9) &10000000000038720000000176×220 38720 4:5 &1000000000000014800000058 (148) phone display, Sony Ericsson W810i &100000000000000011899993.0 (1.19) &100000000000000014800003.8 (1.48) &100000000000000020000005.1 (2.0) &10000000000076800000000240×320 76800 4:5 &1000000000000020000000079 (200) phone display, Nokia 6300, Sony Ericsson W850i & W890i, Apple iPod Nano 3rd & 4th generation &100000000000000011999993.0 (1.2) &100000000000000016000004.1 (1.6) &100000000000000021000005.3 (2.1) &10000000000036608000000176×208 36608 11:13 &1000000000000013000000051 (130) phone display, Nokia N70, Nokia N72 &100000000000000013600003.5 (1.36) &100000000000000016000004.1 (1.6) &100000000000000021000005.3 (2.1) &10000000000146432000000352×416 146432 11:13 &10000000000000259000000102 (259) phone display, Nokia N80, Nokia E70, Nokia N90 &100000000000000013600003.5 (1.36) &100000000000000016000004.1 (1.6) &100000000000000024599996.2 (2.46) &10000000000307200000000640×480 307200 4:3 &10000000000000328000000129 (328) phone display, Nokia E6 &100000000000000019700005.0 (1.97) &100000000000000014800003.8 (1.48) &100000000000000025000006.4 (2.5) &10000000000123060000000420×293 123060 3:2 &1000000000000020500000081 (205) camera display, Sony MVC-CD300 and Sony DSC-W7 approximate &100000000000000020499995.2 (2.05) &100000000000000014299993.6 (1.43) &100000000000000026000006.6 (2.6) &10000000000076800000000240×320 76800 3:4 &1000000000000015400000061 (154) phone display, Nokia N95 &100000000000000015600004.0 (1.56) &100000000000000020800005.3 (2.08) &100000000000000027000006.9 (2.7) &10000000000076800000000320×240 76800 4:3 &1000000000000014800000058 (148) camera display Nikon D5000 &100000000000000021600005.5 (2.16) &100000000000000016200004.1 (1.62) &100000000000000027999997.1 (2.8) &10000000000076800000000240×320 76800 3:4 &1000000000000014300000056 (143) phone display, Nokia N92, Nokia N95 8GB, Nokia N96, HTC Wizard, HTC Tattoo, HTC Touch2 &100000000000000016799994.3 (1.68) &100000000000000022400005.7 (2.24) &100000000000000027999997.1 (2.8) &10000000000307200000000480×640 307200 3:4 &10000000000000286000000113 (286) phone display, HTC Touch Diamond, Touch pro, Neo 1973, Neo FreeRunner, Glofiish M800 &100000000000000016799994.3 (1.68) &100000000000000022400005.7 (2.24) &100000000000000027999997.1 (2.8) &10000000000384000000000800×480 384000 3:5 &10000000000000333000000131 (333) phone display, LG LU1400 &100000000000000023999996.1 (2.4) &100000000000000014399993.7 (1.44) &100000000000000030000007.6 (3) &10000000000409920000000480×854 409920 16:9 &10000000000000327000000129 (327) phone display, Sharp 930SH, Sharp 934SH, Sharp 936SH &100000000000000030000007.6 (3.0) &10000000000230208000000528×436 230208 17:14 &1000000000000022800000090 (228) camera display, Sony DSC-H50 [(approximate) &100000000000000030000007.6 (3.0) &10000000000307200000000640×480 307200 4:3 &10000000000000267000000105 (267) camera display, Nikon D90 &100000000000000030000007.6 (3.0) &10000000000384000000000480×800 384000 3:5 &10000000000000311000000122 (311) phone display, Toshiba Portege G900, Sony Ericsson Xperia X1 &100000000000000031000007.9 (3.1) &10000000000384000000000800×480 384000 3:5 &10000000000000300000000120 (300) phone display, Samsung Jet (S8000) &100000000000000031000007.9 (3.1) &10000000000153600000000480×320 153600 2:3 &1000000000000018600000073 (186) phone display, Palm Pre &100000000000000032000008.1 (3.2) &10000000000409920000000480×854 409920 16:9 &10000000000000306000000120 (306) phone display, Sharp SX862 &100000000000000032000008.1 (3.2) &10000000000153600000000320×480 153600 2:3 &1000000000000018000000071 (180) phone display, HTC Dream, HTC Magic, HTC Hero &100000000000000032000008.1 (3.2) &10000000000384000000000480×800 384000 3:5 &10000000000000292000000115 (292) phone display, HTC Touch Diamond2 &100000000000000032000008.1 (3.2) &10000000000153600000000320×480 332800 2:3 &1000000000000018000000071 (180) phone display, HTC Wildfire S, Sony Ericsson Live With Walkman &100000000000000032999998.4 (3.3) &10000000000130560000000272×480 130560 9:16 &1000000000000016700000066 (167) media player display, Zune HD &100000000000000035000008.9 (3.5) &10000000000153600000000320×480 153600 2:3 &1000000000000016300000064 (163) phone display, Apple iPhone & iPhone 3G, Apple iPod Touch, Samsung Galaxy Ace (S5830) &100000000000000035000008.9 (3.5) &10000000000614400000000640×960 614400 2:3 &10000000000000326000000128 (326) phone display, Apple iPhone 4 &100000000000000035000008.9 (3.5) &10000000000614400000000640×960 614400 2:3 &10000000000000326000000128 (326) phone display, Sharp IS03 &100000000000000035000008.9 (3.5) &10000000000230400000000640×360 230400 9:16 &1000000000000021000000083 (210) phone display, Sony Ericsson Satio, Nokia N97, Nokia 701 &100000000000000035000008.9 (3.5) &10000000000384000000000480×800 384000 3:5 &10000000000000267000000105 (267) phone display, Nokia N900, ZTE Blade &100000000000000036000009.1 (3.6) &10000000000384000000000480×800 384000 3:5 &10000000000000259000000102 (259) phone display, HTC Touch Pro2, Casio G'zOne Commando &100000000000000037000009.4 (3.7) &10000000000384000000000480×800 384000 3:5 &1000000000000025200000099 (252) phone display, HTC Desire S, Samsung Wave II S8530 &100000000000000037000009.4 (3.7) &10000000000409920000000854×480 409920 16:9 &10000000000000265000000104 (265) phone display Motorola Droid, Sony Ericsson Xperia Neo V &100000000000000037999999.7 (3.8) &10000000000130560000000480×272 130560 16:9 &1000000000000014500000057 (145) handheld game console display, Sony PSP Go &100000000000000037999999.7 (3.8) &10000000000384000000000480×800 384000 3:5 &1000000000000024600000097 (246) phone display, HTC Touch HD &1000000000000000400000010 (4) &10000000000491520000000480×1024 491520 32:15 &10000000000000283000000111 (283) phone display, Sharp AQUOS 941SH &1000000000000000400000010 (4.0) &10000000000230400000000640×360 230400 16:9 &1000000000000018300000072 (183) phone display, Nokia E7 &1000000000000000400000010 (4.0) &10000000000518400000000960×540 518400 16:9 &10000000000000275000000108 (275) phone display, Motorola Atrix 4G &1000000000000000409999910 (4.1) &10000000000384000000000800×480 384000 5:3 &1000000000000022800000090 (228) phone display, Nokia 770, N800 & N810 &1000000000000000429999911 (4.3) &10000000000409920000000854×480 409920 16:9 &1000000000000022800000090 (228) phone display, Motorola Droid X &1000000000000000450000011 (4.5) &10000000000921600000000720×1280 921600 9:16 &10000000000000329000000130 (329) phone display, LG Optimus LTE &1000000000000000429999911 (4.3) &10000000000130560000000480×272 130560 16:9 &1000000000000012800000050 (128) handheld game console display, Sony PSP &1000000000000000429999911 (4.3) &10000000000384000000000800×480 384000 5:3 &1000000000000021700000085 (217) phone display, HTC HD2, HTC Evo, HTC Desire HD, Open Pandora, Samsung SWD-M100 &1000000000000000429999911 (4.3) &10000000000518400000000540×960 518400 9:16 &10000000000000256000000101 (256) phone display, Motorola Droid RAZR, Panasonic ELUGA &1000000000000000429999911 (4.3) &10000000000921600000000720×1280 921600 9:16 &10000000000000342000000135 (342) phone display, HTC Rezound &1000000000000000429999911 (4.3) &10000000000921600000000720×1280 921600 9:16 &10000000000000342000000135 (342) phone display, Sony XPERIA S &1000000000000000450000011 (4.5) &100000000006144000000001024×600 614400 17:10 &10000000000000264000000104 (264) umpc display, Sony VAIO UX series &1000000000000000465000011.8 (4.65) &10000000000921600000000720×1280 921600 9:16 &10000000000000316000000124 (316) phone display, Galaxy Nexus &1000000000000000500000013 (5.0) &10000000000480000000000600×800 480000 3:4 &1000000000000020000000079 (200) ebook display, E-Ink screens (Sony PRS300, Bookeen Cybook Opus) &1000000000000000529999913 (5.3) &10000000001024000000000800×1280 1024000 10:16 &10000000000000285000000112 (285) phone display, Galaxy Note &100000000000000028100007.1 (2.81) &1000000000000000449000011.4 (4.49) &1000000000000000559999914 (5.6) &100000000010240000000001280×800 1024000 16:10 &10000000000000270000000110 (270) notebook display, Fujitsu Lifebook U820 &1000000000000000600000015 (6.0) &10000000000480000000000600×800 480000 3:4 &1000000000000016700000066 (167) ebook display, Amazon Kindle, Bookeen Cybook Gen3, and Sony PRS505, PRS600 & PRS700 series &1000000000000000700000018 (7.0) &10000000000345600000000720×480 345600 3:2 &1000000000000012400000049 (124) notebook display &1000000000000000700000018 (7.0) &10000000000384000000000800×480 384000 5:3 &1000000000000013300000052 (133) notebook display, ASUS Eee PC 701 &1000000000000000800000020 (8.0) &100000000012288000000001600×768 1228800 25:12 &1000000000000022200000087 (222) notebook display, Sony VAIO P series &1000000000000000890000023 (8.9) &100000000006144000000001024×600 614400 128:75 &1000000000000013300000052 (133) notebook display, Asus Eee PC 900 &1000000000000000890000023 (8.9) &100000000009830400000001280×768 983040 5:3 &1000000000000016800000066 (168) notebook display, Fujitsu Lifebook P1620 &1000000000000000969999925 (9.7) &100000000007864320000001024×768 786432 4:3 &1000000000000013200000052 (132) tablet display, Apple iPad &1000000000000000969999925 (9.7) &100000000031457280000002048×1536 3145728 4:3 &10000000000000264000000104 (264) tablet display, Apple iPad (3rd generation) &1000000000000000969999925 (9.7) &100000000009888000000001200×824 988800 16:11 &1000000000000015000000059 (150) ebook display, Amazon Kindle DX &1000000000000001009999926 (10.1) &100000000006144000000001024×600 614400 128:75 &1000000000000011800000046 (118) notebook display, also 10.0" or 10.2", Toshiba NB200, Asus Eee PC 1000 &1000000000000001009999926 (10.1) &100000000010240000000001280×800 1024000 8:5 &1000000000000014900000059 (149) tablet display, Asus Eee Pad Transformer, Asus Eee Pad Transformer Prime, Asus Transformer Pad 300 Series &1000000000000001009999926 (10.1) &100000000023040000000001920×1200 2304000 8:5 &1000000000000022400000088 (224) tablet display, Asus Transformer Pad Infinity &1000000000000001009999926 (10.1) &100000000010490880000001366×768 1049088 16:9 &1000000000000015500000061 (155) notebook display &1000000000000001109999928 (11.1) &100000000010490880000001366×768 1049088 16:9 &1000000000000014100000056 (141) notebook display, Sony VAIO X series &1000000000000001159999929 (11.6) &100000000010490880000001366×768 1049088 16:9 &1000000000000014100000056 (141) notebook display, Asus Eee PC 1101HA &1000000000000001209999931 (12.1) &100000000007864320000001024×768 786432 4:3 &1000000000000010600000042 (106) notebook display &1000000000000001209999931 (12.1) &100000000010240000000001280×800 1024000 16:10 &1000000000000012500000049 (125) notebook display &1000000000000001209999931 (12.1) &100000000010490880000001366×768 1049088 16:9 &1000000000000013000000051 (130) notebook display, ASUS Eee PC 1201PN &1000000000000001209999931 (12.1) &100000000014700000000001400×1050 1470000 4:3 &1000000000000014500000057 (145) notebook display, Toshiba Portege M400 &1000000000000001250000032 (12.5) &100000000010490880000001366×768 1049088 16:9 &1000000000000012500000049 (125) notebook display, Thinkpad X220 &1000000000000001309999933 (13.1) &100000000010490880000001366×768 1049088 16:9 &1000000000000012000000047 (120) notebook display, Sony VAIO Z series &1000000000000001309999933 (13.1) &100000000014400000000001600×900 1440000 16:9 &1000000000000014000000055 (140) notebook display, Sony VAIO Z series &1000000000000001309999933 (13.1) &100000000020736000000001920×1080 2073600 16:9 &1000000000000016800000066 (168) notebook display, Sony VAIO Z series &1000000000000001330000034 (13.3) &100000000007864320000001024×768 786432 4:3 &1000000000000009600000038 (96) notebook display &1000000000000001330000034 (13.3) &100000000010240000000001280×800 1024000 16:10 &1000000000000011300000044 (113) notebook display, Apple MacBook &1000000000000001330000034 (13.3) &100000000010490880000001366×768 1049088 16:9 &1000000000000011700000046 (117) notebook display, Sony VAIO Y series &1000000000000001330000034 (13.3) &100000000012960000000001440×900 1296000 16:10 &1000000000000012700000050 (127) notebook display, Apple MacBook Air &1000000000000001409999936 (14.1) &100000000007864320000001024×768 786432 4:3 &1000000000000009000000035 (90) notebook display &1000000000000001409999936 (14.1) &100000000010240000000001280×800 1024000 16:10 &1000000000000010700000042 (107) notebook display &1000000000000001409999936 (14.1) &100000000010490880000001366×768 1049088 16:9 &1000000000000011100000044 (111) notebook display &1000000000000001409999936 (14.1) &100000000014700000000001400×1050 1470000 4:3 &1000000000000012400000049 (124) notebook display &1000000000000001409999936 (14.1) &100000000012960000000001440×900 1296000 16:10 &1000000000000012000000047 (120) notebook display, DELL Inspiron 14 series &1000000000000001409999936 (14.1) &100000000014400000000001600×900 1440000 16:9 &1000000000000013000000051 (130) notebook display, DELL Inspiron 14 series &1000000000000001409999936 (14.1) &100000000019200000000001600×1200 1920000 4:3 &1000000000000014200000056 (142) notebook display, DELL Inspiron 4100 series &1000000000000001500000038 (15.0) &100000000007864320000001024×768 786432 4:3 &1000000000000008500000033 (85) monitor display &1000000000000001500000038 (15.0) &100000000007864320000001024×768 786432 4:3 &1000000000000008500000033 (85) notebook display, monitor display &1000000000000001500000038 (15.0) &100000000014700000000001400×1050 1470000 4:3 &1000000000000011700000046 (117) notebook display &1000000000000001500000038 (15.0) &100000000019200000000001600×1200 1920000 4:3 &1000000000000013300000052 (133) notebook display, monitor display &1000000000000001500000038 (15.0) &100000000031457280000002048×1536 3145728 4:3 &1000000000000017100000067 (171) notebook display, IBM R50p &1000000000000001519999939 (15.2) &100000000008847360000001152×768 884736 3:2 &1000000000000009100000036 (91) notebook display, Apple PowerBook G4 &1000000000000001519999939 (15.2) &100000000010931200000001280×854 1093120 3:2 &1000000000000010100000040 (101) notebook display &1000000000000001540000039 (15.4) &100000000010240000000001280×800 1024000 16:10 &1000000000000009800000039 (98) notebook display &1000000000000001540000039 (15.4) &100000000012960000000001440×900 1296000 16:10 &1000000000000011000000043 (110) notebook display &1000000000000001540000039 (15.4) &100000000017640000000001680×1050 1764000 16:10 &1000000000000012900000051 (129) notebook display &1000000000000001540000039 (15.4) &100000000023040000000001920×1200 2304000 16:10 &1000000000000014700000058 (147) notebook display, Lenovo T61p &1000000000000001559999940 (15.6) &100000000010490880000001366×768 1049088 16:9 &1000000000000010000000039 (100) notebook display, also Sony VAIO E Series (&1000000000000001550000015.5 in (390 mm)) &1000000000000001559999940 (15.6) &100000000014400000000001600×900 1440000 16:9 &1000000000000011800000046 (118) notebook display &1000000000000001559999940 (15.6) &100000000020736000000001920×1080 2073600 16:9 &1000000000000014100000056 (141) notebook display &1000000000000001600000041 (16.0) &100000000010490880000001366×768 1049088 16:9 &1000000000000009800000039 (98) notebook display &1000000000000001600000041 (16.0) &100000000020736000000001920×1080 2073600 16:9 &1000000000000013800000054 (138) notebook display &1000000000000001639999942 (16.4) &100000000014400000000001600×900 1440000 16:9 &1000000000000011200000044 (112) notebook display, Sony VAIO F series &1000000000000001639999942 (16.4) &100000000020736000000001920×1080 2073600 16:9 &1000000000000013400000053 (134) notebook display, Sony VAIO F series &1000000000000001700000043 (17.0) &100000000007864320000001024×768 786432 4:3 &1000000000000007500000030 (75) monitor display &1000000000000001700000043 (17.0) &100000000013107200000001280×1024 1310720 5:4 &1000000000000009600000038 (96) monitor display &1000000000000001359999935 (13.6) &1000000000000001019999926 (10.2) &1000000000000001700000043 (17.0) &100000000019200000000001600×1200 1920000 4:3 &1000000000000011800000046 (118) monitor display &1000000000000001700000043 (17.0) &100000000012960000000001440×900 1296000 16:10 &1000000000000010000000039 (100) notebook display &1000000000000001700000043 (17.0) &100000000017640000000001680×1050 1764000 16:10 &1000000000000011700000046 (117) notebook display &1000000000000001700000043 (17.0) &100000000020736000000001920×1080 2073600 16:9 &1000000000000013000000051 (130) notebook display &1000000000000001700000043 (17.0) &100000000023040000000001920×1200 2304000 16:10 &1000000000000013300000052 (133) notebook display &1000000000000001730000044 (17.3) &100000000014400000000001600×900 1440000 16:9 &1000000000000010600000042 (106) notebook display &1000000000000001730000044 (17.3) &100000000020736000000001920×1080 2073600 16:9 &1000000000000012700000050 (127) notebook display &1000000000000001839999947 (18.4) &100000000015876000000001680×945 1587600 16:9 &1000000000000010500000041 (105) notebook display &1000000000000001839999947 (18.4) &100000000020736000000001920×1080 2073600 16:9 &1000000000000012000000047 (120) notebook display &1000000000000001900000048 (19.0) &100000000007864320000001024×768 786432 4:3 &1000000000000006700000026 (67) monitor display &1000000000000001900000048 (19.0) &100000000013107200000001280×1024 1310720 5:4 &1000000000000008600000034 (86) monitor display &1000000000000001519999939 (15.2) &1000000000000001140000029 (11.4) &1000000000000001900000048 (19.0) &100000000012960000000001440×900 1296000 16:10 &1000000000000008900000035 (89) monitor display &1000000000000001655999942.1 (16.56) &1000000000000000932000023.7 (9.32) &1000000000000002010000051 (20.1) &100000000017640000000001680×1050 1764000 16:10 &1000000000000009900000039 (99) monitor display &1000000000000002100000053 (21) &100000000007864320000001024×768 786432 4:3 &1000000000000006100000024 (61) monitor display &1000000000000002100000053 (21) &100000000013107200000001280×1024 1310720 5:4 &1000000000000007800000031 (78) monitor display &1000000000000002100000053 (21) &100000000019200000000001600×1200 1920000 4:3 &1000000000000009500000037 (95) monitor display &1000000000000002100000053 (21) &100000000027648000000001920×1440 2764800 4:3 &1000000000000011400000045 (114) monitor display &1000000000000002150000055 (21.5) &100000000020736000000001920×1080 2073600 16:9 &1000000000000010200000040 (102) monitor display, Apple iMac &1000000000000002200000056 (22) &100000000017640000000001680×1050 1764000 16:10 &1000000000000009000000035 (90) monitor display &1000000000000001917000048.7 (19.17) &1000000000000001077999927.4 (10.78) &1000000000000002200000056 (22) &100000000031457280000002048×1536 3145728 4:3 &1000000000000012000000047 (120) monitor display, A201HT &1000000000000002200000056 (22) &100000000092160000000003840×2400 9216000 16:10 &1000000000000020500000081 (205) monitor display, IBM T220/T221 LCD monitors &1000000000000001917000048.7 (19.17) &1000000000000001077999927.4 (10.78) &1000000000000002300000058 (23) &100000000020736000000001920×1080 2073600 16:9 &1000000000000009600000038 (96) monitor display &1000000000000002300000058 (23) &100000000023040000000001920×1200 2304000 16:10 &1000000000000009800000039 (98) monitor display &1000000000000002300000058 (23) &100000000021504000000002048×1050 2150400 16:9 &1000000000000010200000040 (102) monitor display &1000000000000002400000061 (24) &100000000007864320000001024×768 786432 4:3 &1000000000000005300000021 (53) monitor display &1000000000000002400000061 (24) &100000000023040000000001920×1200 2304000 16:10 &1000000000000009400000037 (94) monitor display &1000000000000002092000053.1 (20.92) &1000000000000001175999929.9 (11.76) &1000000000000002400000061 (24) &100000000027648000000001920×1440 2764800 4:3 &1000000000000010000000039 (100) monitor display &1000000000000002500000064 (25) &100000000013107200000001280×1024 1310720 5:4 &1000000000000006600000026 (66) monitor display &1000000000000002600000066 (26) &100000000023040000000001920×1200 2304000 16:10 &1000000000000008700000034 (87) monitor display &1000000000000002700000069 (27) &100000000023040000000001920×1200 2304000 16:10 &1000000000000008400000033 (84) monitor display &1000000000000002700000069 (27) &100000000023592960000002048×1152 2359296 16:9 &1000000000000008700000034 (87) monitor display &1000000000000002700000069 (27) &100000000036864000000002560×1440 3686400 16:9 &1000000000000010900000043 (109) monitor display, Apple iMac &1000000000000002700000069 (27) &100000000036864000000002560×1440 3686400 16:9 &1000000000000010900000043 (109) monitor display, Dell UltraSharp U2711 &1000000000000003000000076 (30) &100000000040960000000002560×1600 4096000 16:10 &1000000000000010100000040 (101) monitor display &1000000000000003200000081 (32) &100000000009835200000001366×720 1049088 16:9 &1000000000000004800000019 (48) television, 720p &1000000000000003200000081 (32) &100000000020736000000001920×1080 2073600 16:9 &1000000000000008100000032 (81) television, 1080i, 1080p &1000000000000003700000094 (37) &100000000020736000000001920×1080 2073600 16:9 &1000000000000006000000024 (60) television, 1080i, 1080p &10000000000000042000000110 (42) &10000000000307200000000640×480 307200 4:3 &100000000000000190000007.5 (19) television, 480i &10000000000000042000000110 (42) &10000000000409920000000854×480 409920 16:9 &100000000000000230000009.1 (23) television, 480p &10000000000000042000000110 (42) &10000000000414720000000720×576 414720 5:4 &100000000000000220000008.7 (22) television, 576i, 576p &10000000000000042000000110 (42) &100000000009216000000001280×720 921600 16:9 &1000000000000003500000014 (35) television, 720p &10000000000000042000000110 (42) &100000000020736000000001920×1080 2073600 16:9 &1000000000000005200000020 (52) television, 1080i, 1080p &10000000000000050000000130 (50) &100000000020736000000001920×1080 2073600 16:9 &1000000000000004400000017 (44) television, 1080p &10000000000000050000000130 (50) &100000000082944000000003840×2160 2073600 16:9 &1000000000000008800000035 (88) television, 2160p &10000000000000055000000140 (55) &100000000020736000000001920×1080 2073600 16:9 &1000000000000004000000016 (40) television, 1080p &10000000000000055000000140 (55) &100000000082944000000003840×2160 2073600 16:9 &1000000000000008000000031 (80) television, 2160p
So… the site I’m working on has one of those “increase text size” controls. On this project it’s turned out to be one of those features that shows up in comps and somehow falls through the cracks until later on in the project cycle. Situation normal, really, as it isn’t a big feature. It’s just one of those things that needs to be buttoned up before the site can go live.
Anyway, I was thinking about how to do implement it the other day. I haven’t done one of these in a long time and the only other time I did one it involved crafting separate, albeit small, style sheets for the larger text sizes. I didn’t want to go that way again. Basically, I just didn’t want to write new style sheets- even small ones.
What’s a fella to do?
zoom
So, thinking about it a little bit, I seized upon using the non-standard CSS zoom property. Supported in Internet Explorer (zoom:1 is often used for a hasLayout toggle) and Webkit browsers, it would represent a simple (1 line!) CSS solution to this problem. It’s also one that I like better aesthetically as the site looks the same, just bigger. I figure there’s a reason all browsers have moved to this behavior when hitting ctrl+.
The problem was figuring out an equivalent for FireFox and Opera which don’t support zoom
Enter CSS 2D Transform
A little searching and experimenting later I came up with the idea of using CSS Transforms and the scale value to approximate zoom in browsers that lack support.
Let’s see how I did it.
As you go through the following keep in mind this hasn’t actually gone through testing yet so something weird could yet shake out. I just wrote this code yesterday, so you guys can be my sanity check.
Also, is anyone else doing this?
Here’s the markup. We had this done weeks ago.
<!-- yes, we get the gas face for href="#" I don't like them either. I'll rewrite it to use just LIs, I swear. --> <ul id="font-size"><li class="text">Text Size:</li> <li><a href="#" class="default">default font size</a></li> <li><a href="#" class="larger">larger font size</a></li> <li><a href="#" class="largest">largest font size</a></li> </ul>The first thing I did was write a small chunk of code that runs on $(document).ready()
(yes, this is a jQuery project.)
//using the jQuery cookie plugin to get a pre-set value; var fontSize=$.cookie('font_size'); //if it exists, set the body.className right now //and... //the user gets their size of choice right away if (fontSize) { $(document.body) .removeClass("largest larger default") .addClass(fontSize); } $("#font-size li a").click( function(e){ var $body = $(document.body), newClass = this.className; //if it doesn't already have the chosen class if (!$body.hasClass(newClass)) { //clear any old ones and add the new one $body .removeClass("largest larger default") .addClass(newClass); } //saving the choice in a cookie $.cookie('font_size',this.className); //and finally, stop the clicks e.preventDefault(); } )Cool. So far so good. We’ve got classes on the body indicating how big the user wants to see the site.
Before we look at the CSS, there’s one more bit of JavaScript we need to look at as I almost immediately envisioned a problem with the above scenario.
If i was using CSS Transforms to scale the pages in Firefox and then Firefox eventually implemented zoom, things would get wonky. We don’t want that. I had to future-proof the code a little bit.
So, what I needed was a test for the presence of a valid zoom CSS property. Turning to Modernizr (since it was already in use on the site) I used the handy Modernizr.addTest method to test for zoom. Here’s the one I cobbled together.
Modernizr.addTest('zoom', function () { //create a div var test = document.createElement('div'); //if there's a valid property in the browser //it will return "" //undefined means the browser doesn't know //what you're talking about if (test.style.zoom === undefined) { delete test; return false; } delete test; return true; });And finally, we’ve got the style sheet.
/* we add a .default class, so we can reset the page with the mechanism defined above */ body, body.default { font:13px/1.231 arial, helvetica, sans-serif; color:#222; background:url(images/page-bg.jpg) center repeat-y; min-width:960px; overflow-x:hidden; } /* here's our class for browsers without a zoom property, this sets the transform's origin. In this case it defines the point from which our scale will happen. We want it to row from the center and from the top, so 50% and 0 it is. */ .no-zoom body { -o-transform-origin:50% 0; -moz-transform-origin:50% 0; } /* classes for browsers with zoom */ .zoom body.larger { zoom:110%; } .zoom body.largest { zoom:125%; } /* and classes for browsers that don't support zoom */ .no-zoom body.larger { -o-transform: scale(1.1); -moz-transform: scale(1.1); transform: scale(1.1); } .no-zoom body.largest { -o-transform: scale(1.25); -moz-transform: scale(1.25); transform: scale(1.25); }And that’s that. Here’s a quick demo to see it in action. You can also view source here.
Performance
I did a quick V8 Benchmark comparing scaled/zoomed performance in several browsers to see if there are any issues. The following table shows that there really isn’t much difference. Clearly this isn’t a definitive test as it’s only a small run of tests in one benchmark on one machine, but it was nice that nothing shook out in this first pass. I’m going to look at doing a DOM heavy test as well as something with some animation (maybe even Canvas?)
Browser no zoom/scale zoom:1.5 transform:scale(1.5); Chrome 8.0.552.215 5587 5642 5782 Firefox 3.6.13 594 NA 653 Internet Explorer 8 117
120
NA Internet Explorer Platform Preview version 1.9.8023.6000 2243
2280
2292
Safari 5.03 2839 2874 2796 Opera 10.63 4071 NA 4110 I kind of like it.
Follow @robreact
A pixel is not a pixel is not a pixel
Yesterday John Gruber wrote about the upped pixel density in the upcoming iPhone (960x640 instead of 480x320), and why Apple did this. He also wondered what the consequences for web developers would be.
Now I happen to be deeply engaged in cross-browser research of widths and heights on mobile phones, and can state with reasonable certainty that in 99% of the cases these changes will not impact web developers at all.
The remaining 1% could be much more tricky, but I expect Apple to cater to this problem by inserting an intermediate layer of pixels. (Later John pointed out that such a layer already exists on Android.)
One caveat before we start: because they’re unimportant to web developers I have mostly ignored the formal screen sizes, and I’m not really into disucssing the ins and outs of displays, pixel densities, and other complicated concepts. So I might use the wrong terminology here, for which I apologise in advance.
What web developers need
I do know what web developers are interested in, however. They need CSS pixels. That is, the “pixels” that are used in CSS declarations such as width: 300px or font-size: 14px.
These pixels have nothing to do with the actual pixel density of the device, or even with the rumoured upcoming intermediate layer. They’re essentially an abstract construct created specifically for us web developers.
It’s easiest to explain when we consider zooming. If the user zooms in, an element with width: 300px takes up more and more of the screen, and thus becomes wider and wider when measured in device (physical) pixels. In CSS pixels, however, the width remains 300px, and the zooming effect is created by expanding CSS pixels as much as is needed.
When the zooming factor is exactly 100%, one CSS pixel equals one device pixel (though the upcoming intermediate layer will take the place of device pixels here.) The image below depicts that. Not much to see here, since one CSS pixel exactly overlaps one device pixel.
(I should probably warn you that “zoom 100%” has little meaning in web development. Zooming level is unimportant to us; what we need to know is how many CSS pixels currently fit on the screen.)
The following two images illustrate what happens when the user zooms. The first shows device pixels (the dark blue background) and CSS pixels (the semi-transparent foreground) when the user has zoomed out. The CSS pixels have become smaller; one device pixel overlaps several CSS pixels. The second image shows device and CSS pixels when the user has zoomed in. One CSS pixel now overlaps several device pixels.
Thus our element with width: 300px is always exactly 300 CSS pixels wide, and how many device pixels that equals is up to the current zooming factor.
(You can calculate that factor by dividing screen.width by window.innerWidth — on the iPhone. Browser incompatibilities are rife here; expect a full report in the not-too-distant future. Besides, as a web developer you’re not interested in the zooming factor, but in how many pixels (device or CSS) fit on the device screen.)
This system will not change. If it did, all iPhone-optimised sites would become severely un-optimised in a hurry, and that’s something Apple wants to prevent at all cost.
Thus, a fully zoomed-out website would still display at 980 CSS pixels, and how many device pixels that equals is unimportant to us.
The tricky bits
However, there are two tricky bits: the device-width media query and the <meta name="viewport" width="device-width"> tag. Both work with device pixels, and not with CSS pixels, because they report on the context of the web page, and not on its inner CSS workings.
The media query
The device-width media query measures the width of the device in device pixels. The width media query measures the total width of the page in CSS pixels, which, for reasons I’ll explain later, is at least 980px on the iPhone.
The device-width media query works as follows:
div.sidebar { width: 300px; } @media all and (max-device-width: 320px) { // styles assigned when device width is smaller than 320px; div.sidebar { width: 100px; } }Now the sidebar is 300 CSS pixels wide, except when the device width is 320 device pixels or less, in which case it becomes 100 CSS pixels wide. (You stil follow? This is complicated.)
By the way, in theory you could use a media query that queries the device screen in centimeters or inches (@media all and (max-device-width: 9cm)). Unfortunately it seems badly to outright unsupported, even by the iPhone. The problem here is that physical units such as inches are usually translated to (CSS) pixels; thus width: 1in equals 96 pixels on all browsers I tested so far (and that’s quite a few). So these media queries are unreliable.
The <meta> tag
In general <meta name="viewport" width="device-width"> is even more useful. This tag, originally Apple-proprietary but meanwhile supported by many more mobile browsers, actually makes the layout viewport fit the device exactly.
Now what is the layout viewport? It’s the area (in CSS pixels) that the browser uses to calculate the dimensions of elements with percentual width, such as div.sidebar {width: 20%}. It’s usually quite a bit larger than the device screen: 980px on the iPhone, 850px on Opera, 800 on Android, etc.
If you add <meta name="viewport" width="device-width">, the width of this layout viewport is constrained to the device width in device pixels; 320 of them in the iPhone’s case.
That matters if your pages are narrow enough to fit in the screen. Take this page without any CSS width statement and without the <meta> tag. It stretches over the full available width of the layout viewport.
This is probably not what you want. You want to fit the text nicely on the screen. That’s the task of <meta name="viewport" width="device-width">. When you add it, the layout viewport is contracted (to 320px in the case of the iPhone), and the text fits.
Apple’s changes
Now what impact will Apple’s resolution changes have on the device-width media query and the <meta> tag? Of course I cannot be certain, but I expect that nothing will change for web developers.
The <meta> tag
The <meta> tag is easiest to explain. Apple has deliberately invented it precisely in order to allow people to fit their content on an iPhone screen, and has pushed it with developers. That means that it can’t afford to change the device width as read out by the <meta> tag now.
In fact, the Nexus One has already blazed a trail for Apple to follow. Its official screen width (in portrait mode) is 480px, but when you apply the <meta> tag it acts as if the screen width is 320px, 2/3rds of the official width.
If I understand correctly, this is what John Gruber is saying when talking about the Nexus’s display and its missing one sub-pixel and thus 1/3rd less pixels. That fits the Nexus interpretation of the <meta> tag exactly.
So basically Google has already inserted a layer of what are apparently called dips; device-independent pixels. This layer comes between the official, reported screen size and the CSS pixels web developers work with.
I expect the new iPhone to copy the Nexus trick and report the screen size as 320px (half of the formal resolution, in other words) when queried by the <meta> tag. It’s half and not two-thirds because the pixel density of the new iPhone is higher than the Nexus (or something).
The media query
That leaves the device-width media query as the sole problem area. On the Nexus it uses 480px as the screen width, despite the fact that here, too, 320px may be more appropriate. We’ll have to see what Apple does here.
The more fundamental question is whether the dips are also going to be used for media queries. On the whole I’d say we want that; formal device size is unimportant to web developers: we want to know how much content we can get on the screen, and it seems dips are most suited for that.
Unfortunately the Nexus does not do that right now; as far as media queries are concerned the device-width is still 480px, and not 320px. But maybe Apple can solve this problem for web developers.
So the situation is quite clear for normal websites and for those that use the <meta> tag; less clear when it comes to media queries.
Stay tuned.
Automatically adapt your existing website images for mobile devices. No mark-up changes needed. For use with CSS3 Responsive Designs.
This entry has been deprecated:
Please use 320 and Up instead.
Making layouts responsive using CSS3 Media Queries are a big part of the work that I’m doing for the Hardboiled Web Design site in the run up to the book’s launch.
Since I started using Media Queries extensively over the last few months, I’ve revised the queries several times for each project, so it made sense to build a boilerplate to use as a starting point. These hardboiled CSS3 Media Queries are empty placeholders for targeting the devices and attributes I’m interesting in making responsive designs for right now.
They’re part of a wider toolkit that I’ll be releasing at the same time as the book. But for now, you can download and incorporate these override queries at the bottom of your existing CSS files. Download the CSS file
/* Smartphones (portrait and landscape) ----------- */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) { /* Styles */ } /* Smartphones (landscape) ----------- */ @media only screen and (min-width : 321px) { /* Styles */ } /* Smartphones (portrait) ----------- */ @media only screen and (max-width : 320px) { /* Styles */ } /* iPads (portrait and landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) { /* Styles */ } /* iPads (landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) { /* Styles */ } /* iPads (portrait) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) { /* Styles */ } /* Desktops and laptops ----------- */ @media only screen and (min-width : 1224px) { /* Styles */ } /* Large screens ----------- */ @media only screen and (min-width : 1824px) { /* Styles */ } /* iPhone 4 ----------- */ @media only screen and (-webkit-min-device-pixel-ratio : 1.5), only screen and (min-device-pixel-ratio : 1.5) { /* Styles */ }Of course, you might not want all your responsive design styles inside one huge stylesheet. If that’s the case, you can serve alternative stylesheets using the same queries as attributes on your link elements.
<head> <link rel="stylesheet" href="smartphone.css" media="only screen and (min-device-width : 320px) and (max-device-width : 480px)"> <link rel="stylesheet" href="smartphone-landscape.css" media="only screen and (min-width : 321px)"> <link rel="stylesheet" href="smartphone-portrait.css" media="only screen and (max-width : 320px)"> <link rel="stylesheet" href="ipad.css" media="only screen and (min-device-width : 768px) and (max-device-width : 1024px)"> <link rel="stylesheet" href="ipad-landscape.css" media="only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape)"> <link rel="stylesheet" href="ipad-portrait.css" media="only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait)"> <link rel="stylesheet" href="widescreen.css" media="only screen and (min-width : 1824px)"> <link rel="stylesheet" href="iphone4.css" media="only screen and (-webkit-min-device-pixel-ratio : 1.5), only screen and (min-device-pixel-ratio : 1.5)"> </head>Download the CSS file and any comments or suggestions for future improvements would be more than welcome.
Sign-up for email alerts or follow @itshardboiled for more updates and sneak previews.
Designing for the Retina Display (326ppi) July 8, 2010 by Luke WroblewskiFor three generations of the iPhone, Apple kept the screen consistent (320x480 pixels and 3.5 inches diagonal). But now Apple's new iPhone 4 boasts the "highest resolution phone screen ever (960x640 pixels, 3.5 inches diagonal, & an 800:1 contrast ratio)." What's the impact to designers?
But first, why is it an issue? Because of PPI (pixels per inch) or pixel density variations.
"A screen with lower density has fewer available pixels spread across the screen width and height, where a screen with higher density has more — sometimes significantly more — pixels spread across the same area. The density of a screen is important because, other things being equal, a UI element (such as a button) whose height and width are defined in terms of screen pixels will appear larger on the lower density screen and smaller on the higher density screen."Initial Palm and Android smartphones were in the same ballpark as Apple's first set of iPhones so ppi (pixels per inch) was roughly the same across these devices.
- iPhone: 320x480 | 3.5 in | 164ppi
- Palm Pre | 320x480 | 3.1 in 186ppi
- Palm Pixie | 320x400 | 2.63 in | 194ppi
- T-Mobile G1 | 320x480 | 3.2 in | 180ppi
- MyTouch 3G | 320x480 | 3.2 in | 180ppi
- HTC Hero | 320x480 | 3.2 in | 180ppi
The next set of Android phones featured much higher PPI only to be bested by Nokia's next generation of smartphones and finally the iPhone 4.
- Motorola Droid | 480x854 | 3.7 in | 264ppi
- Nexus One | 480x800 | 3.7 in | 252ppi
- HTC Desire | 480x800 | 3.7 in | 252ppi
- Nokia N97 | 360x640 | 3.2 in | 229ppi
- Nokia N900 | 800x480 | 3.5 in | 266ppi
- Apple iPhone 4 | 960x640 | 3.5 in | 326ppi
So how do designers manage these jumps in pixel density? Here's a round-up of recent articles that tackle the issue.
Updated on: March 14 2012 with a few additional resources.
Optimising for High Pixel Density Displays by Optic Swerve outlines a CSS and JavaScript approach for web sites/apps that cater to high density pixel displays.
- Start with a basic fluid CSS design. Tweak for specific ‘device-width’ ranges with Media Queries. Even better, use ‘width’ queries for even further flexibility and easy prototyping. Tweak further with ‘device-pixel-ratio’ queries.
- The ‘text-rendering’ CSS options, specifically ‘optimizeLegibility’ are worth enabling on high pixel density screens.
- Create one large (2x resolution) image and then scale down by 50% (in-browser) via CSS for all pixel density displays. Devices without a perfect ‘2’ pixel ratio will still produce better results than a low-resolution image, for far less work.
- Use the CSS tools at your disposal. They're resolution independent and bandwidth friendly.
Designing for Retina display by Bjango illustrates a workflow for resolution-independent vector graphics in Photoshop.
- Create solid color, pattern or gradient layers with vector masks (just make sure you have snap to pixel turned on, where possible).
- More complex objects get drawn in Illustrator to the exact pixel size, then pasted into Photoshop as a shape layer.
- Even more complex objects, that require multiple colours, get drawn in Illustrator to the exact pixel size, then pasted into Photoshop as a smart object.
- Photoshop Actions can scale designs to 200% quickly.
- Further Q&A about this workflow.
Designing for iPhone 4's Retina Display by Josh Clark (author of Tapworthy) looks at the impact of the Retina Display on iPhone application development.
- Starting in iOS 4, dimensions are measured in “points” instead of pixels. Conveniently enough, the iPhone screen is 320x480 points on both iPhone 4 and older models.
- On iPhone 4, a point is two pixels; draw a one-point line, and it shows up two pixels wide. So: just specify your measurements in points for all devices, and iOS automatically draws everything to the right proportion on the screen.
- To add high-resolution images to your app, you have to include a second set of all your graphic files. For every image in your app, add a second version that’s twice the size, adding @2x to the name.
- Photoshop fans should learn to get comfortable with Illustrator. By building your app graphics in vector format, you can export them in whatever size you like with limited muss or fuss.
How to make your web content look stunning on the iPhone 4’s new Retina display by Aral Balkan outlines the high-level impact of the Retina Display on Web design & development.
- If you want your applications and web sites to look beautiful on the iPhone 4's new retina screen, you're going to have to create high-resolution versions of your bitmaps and/or use vectors.
- You basically have to design liquid interfaces (and interface elements) for your apps.
- SVG can help in creating resolution-independent designs.
- Since browsers do not currently have automatic support for loading high-resolution versions of image and video assets, we can use a combination of CSS media queries and JavaScript for the same effect.
- With CSS3 media queries you can then build Web sites with completely different CSS files based off the pixel-ratio of CSS pixels to device pixels, including higher res artwork as necessary.
- This approach also degrades gracefully, since you can specify the lowres CSS file and then higher res CSS files inside media queries that will be ignored by browsers that don’t understand them.
High DPI Web Sites by Dave Hyatt outlines how the WebKit team is thinking about allowing Web authors to effectively support very high resolution devices.
- Most Web site authors have traditionally thought of a CSS pixel as a device pixel. However as we enter this new high DPI world where the entire UI may be magnified, a CSS pixel can end up being multiple pixels on screen.
- Safari actually supports PDF as an image format (the hands of the clock Dashboard widget are an example of this). However other browsers do not support this format. The agreed-upon standard for scalable graphics on the Web is SVG.
- Our goal with WebKit is to make SVG a first-class image format, so that it can be used anywhere you might use a PNG, a GIF or a JPG.
Targeting the iPhone 4 Retina Display with CSS3 Media Queries by Walt Dickinson shows how to use CSS3 media queries to target the Retina Display.
- In order to preserve the design of existing websites, images are automatically pixel-doubled. And this creates a schism between “device pixels” and “CSS pixels”.
- With CSS3 media queries, you can use device-pixel-ratio, for targeting specific pixel densities. This tells browsers to include High PPi CSS files only if the device pixel ratio is 2 or higher. This CSS file overrides the background images of some of my site’s graphics with higher resolution versions and uses the background-size property to set the correct CSS pixel dimensions.
In What does 320dpi mean to designers? Tim Van Damme provides a list of tricks and techniques for design on the Retina Display.
- Solid lines and drop shadow on text should be 2px wide. Subtle glows however should be 1.5px
- All the objects you design should measure a multitude of 2. Designing a 50×50 pixel circle will turn out to be 25×25 on an older iPhone.
- Try doing as much as you can with code. Drawing gradients and lines and more with pure code delivers performance gains.
- For objects that need an image, you should always provide 2 images, one for each resolution.
- Keep testing the interface you’re designing on an actual iPhone. Save your files on Dropbox. Grab your iPhone, open the Dropbox client, and view them on the device.
If you've come across any other resources on designing for the Retina Display (326ppi), let me know!
Optimising for High Pixel Density Displays.
Recent mobile device releases have raised the bar in terms of display pixel density. The iPhone4 326PPI ‘Retina display’ is getting a lot of (deserved) attention in this respect.
This trend and the concurrent surge in tablet popularity means we're now designing for an extremely wide range of display specifications. High pixel density tablets can't be far away… (UPDATE. The new iPad did this as of March 2012).
In this article we'll discuss a maximum quality, minimum effort CSS and JavaScript approach to web sites/apps that cater for high density pixel displays.
The Pixel Conundrum
With the advent of high pixel density displays the pixel itself is now a relative unit.
According to the CSS 2.1 Specification:
Pixel units are relative to the resolution of the viewing device, i.e., most often a computer display. If the pixel density of the output device is very different from that of a typical computer display, the user agent should rescale pixel values.So, a ‘CSS pixel’ indicates one point on the virtual pixel grid to which our CSS design aligns. This either directly matches the actual device pixel grid on which our content is rendered or it is intelligently scaled.
This has led to the definition of a ‘Density-independent pixel (dip)’. (Android Developers)
A virtual pixel unit that applications can use in defining their UI, to express layout dimensions or position in a density-independent way.iPhone4 was not the first to employ virtual pixels although other implementations often had less convenient scaling factors. 1 virtual pixel could equal 1.5 physical pixels and so on.
A detailed summary of the ‘Pixel is not a pixel’ situation is available on quirksmode.
Fixed vs. Fluid Layouts
Like it or not, fixed layouts now exhibit fluid behaviour on displays that employ density-independent pixels.
The fixed vs. fluid layout argument has been rendered irrelevant.
Fixed layouts will continue to work acceptably on iPhone and other mobile web-enabled devices. The touch interaction method that iOS, Android etc. employ is a great solution. The virtual pixel scaling algorithm does a great job, the end result being the quality that iPhone4 exemplifies.
However, when targeting mobile devices via CSS Media Queries the virtual pixel situation rapidly gets confusing. Fixed layouts were popular because exact ‘pixel perfect’ control was simple, now it's simply not.
What happens if future high pixel density displays require 2.5x scaling or even pixel tripling? How much relative pixel math with awkward ratios can you endure?
Take the plunge, move to simple, logical units (em's, percentages etc.).
Consider Hybrid/Adaptive CSS
This technique enables all the freedom in the world to tweak for specific devices.
- Start with a basic fluid CSS design.
- Tweak for specific ‘device-width’ ranges with Media Queries.
- Even better, use ‘width’ queries for even further flexibility and easy prototyping.
- Tweak further with ‘device-pixel-ratio’ queries.
You'd be safe in the knowledge that the fallback fluid layout would be presentable since it would scale smoothly across multiple devices due to it's independence from pixel ratio.
A great implementation example is the Hicksdesign website.
Text Rendering
Typography is an underrated area of mobile web design. Great text makes a big difference on small displays.
Mobile devices also allow for extreme enlargement (via zoom). This is where high pixel density displays really shine. Text looks extremely smooth at all zoom levels.
The ‘text-rendering’ CSS options, specifically ‘optimizeLegibility’ are worth enabling on high pixel density screens.
Enabling it yields improved support for kerning pairs and ligatures. They look great on iPhone4!
/* Heading kerning pairs and ligatures */h1, h2, h3 { text-rendering: optimizeLegibility; }It degrades gracefully to standard text rendering if not supported. Demo.
Enhanced Typography
Techniques like @font-face are perfect for multi-device typography.
- Headings scale with embedded fonts.
- The commonly used alternative, header images, do not scale attractively.
Combined with carefully chosen fonts, CSS text shadowing and the improved text-rendering declaration, we have some great options for fantastic high resolution typography.
Targeting High Pixel Density Displays
The device-pixel-ratio Media Query can be used to target style for high pixel density displays.
<!-- High pixel density displays --><link rel='stylesheet' href='highRes.css' media='only screen and (-moz-min-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2)' />Note that for the moment vendor prefixes are required. Mozilla and Webkit prefixes work in the same way, but Opera requires the device pixel ratio as a fraction.
The above Media Query is discussed at MiniApps – Targeting iPhone4 using CSS Media Queries.
Media Queries continue to provide a strong starting point for all CSS based device-pixel-ratio and device-width optimisation decisions.
Device pixel ratio can also be queried in JavaScript.
var dpr = 1; if(window.devicePixelRatio !== undefined) dpr = window.devicePixelRatio;Higher Image Quality
The most prominent trick to come out of pixel ratio Media Queries is high-resolution background image substitution.
For example, a website header could vary quality in line with the pixel density of the display it is rendered on.
- Separate images are created for each device pixel ratio we wish to support (e.g. 1x, 1.5x, 2x).
- The default (normal-res) background header is specified via CSS.
- For high pixel density displays, the high-res image is substituted in.
- The image background-size is scaled by the inverse of the device pixel ratio.
- In the case of the iPhone4 the image is twice the resolution, scaled to 50% in the CSS.
This maintains the correct relative size on screen, but results in noticeably improved image definition on screens that support it.
Assuming a desired 100 by 100px (virtual pixels!) image size, the saved image resolutions would be as follows,
/* Pixel ratio of 1. Background size is 100% (of a 100px image) */ #header { background: url(header.png); } /* Pixel ratio of 1.5. Background-size is 1/1.5 = 66.67% (of a 150px image) */ @media only screen and (-moz-min-device-pixel-ratio: 1.5), only screen and (-o-min-device-pixel-ratio: 3/2), only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-device-pixel-ratio: 1.5) { #header { background: url(headerRatio1_5.png); background-size: 66.67%; } } /* Pixel ratio of 2. Background-size is 1/2 = 50% (of a 200px image) */ @media only screen and (-moz-min-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-device-pixel-ratio: 2) { #header { background: url(headerRatio2.png); background-size: 50%; } }
- 1x: 100px
- 1.5x: 150px
- 2x: 200px
There is a problem with this. The device pixel ratio is not always a neat ‘2’ as with the iPhone4. How many images are you willing to produce? Already, just with 1x, 1.5x and 2x, that's three images! This won't get any easier.
The solution? Create one large (2x resolution) image and then scale down by 50% (in-browser) via CSS for all pixel density displays.
Devices without a perfect ‘2’ pixel ratio will still produce better results than a low-resolution image, for far less work.
Browsers (including mobile browsers) have great scaling mechanisms nowadays so the resulting image quality will be good across all devices.
Yes, this does mean greater bandwidth required. Looks vs. performance would require consideration.
Mobile stylesheets shouldn't be using many images anyway, so perhaps this is just a proof-of-concept technique with little real world significance.
Remember that a lot of people on iPhone4s are also now paying for their data!
If pixel ratios exceed 2 in future then consider SVG or a similar technology. Besides, surely 2x is near the maximum? 326ppi is the ‘Retina Display’ after all :-p
‘That's because the Retina display's pixel density is so high, your eye is unable to distinguish individual pixels.’ - Apple Inc.Inline Images
We've taken care of images specified with CSS, but what about standard <img> tags?
If you're happy serving up high-resolution images, then we can use a similar scaling technique. This could be accomplished with the following JavaScript snippet (using jQuery for brevity).
Only enable pixel ratio related JavaScript where necessary. This can easily be done with JavaScript pixel ratio detection. We assume a 1:1 pixel ratio if the browser doesn't support it.
// Query the device pixel ratio. //------------------------------- function getDevicePixelRatio() { if(window.devicePixelRatio === undefined) return 1; // No pixel ratio available. Assume 1:1. return window.devicePixelRatio; } // Process all document images //----------------------------- function processImages() { if(getDevicePixelRatio() > 1) { var images = $('img'); // Scale each image's width to 50%. Height will follow. for(var i = 0; i < images.length; i++) { images.eq(i).width(images.eq(i).width() / 2); } } }All document <img> elements are automatically resized on high pixel density screens. Normal 1:1 screens can either leave the image unscaled, or force the scale of all images via a separate function (included in the source). Your call.
There is a better method. Tag images that are to be high-resolution with a class.
<img class='highRes' />Then target <img> elements tagged with this class with the JavaScript scaling technique.
// Only process tagged document images //------------------------------------- function processTaggedImages() { if(getDevicePixelRatio() > 1) { var images = $('img.highRes'); // Only images with class 'highRes' // Scale each image's width to 50%. Height will follow. for(var i = 0; i < images.length; i++) { images.eq(i).width(images.eq(i).width() / 2); } } }Now for a demonstration. One image is class tagged as 'highRes'. Note, on 1:1 pixel ratio displays, these images will be the same size.
For the full details of how this works, check out the source code.
If you decide to make all your images high resolution and scale by 50% you could have a lot of wasted bandwidth for viewers on 1:1 pixel ratio displays. You do have some flashy waste reducing options, depending mainly on how much work you are prepared to put in.
- Simply link to the same image, which would display it without scaling.
- Display it in a lightbox when clicked.
CSS targeted at mobile devices often scales images anyway. This usually means a single column with images occupying 100% of the device width. If this is your mobile design strategy, stick with it. Just be aware that you can now get higher image quality if required.
There have been suggestions concerning automatic fetching of high resolution images. These techniques do have potential, but until the performance implications (request numbers, 404s etc.) are taken care of then this method is not feasible.
If this could somehow be done on the server side, then it could be very popular. It would also have to include automatic image scaling, so that web designers aren't manually creating many versions of the same image.
Use CSS Enhancements
- Gradients
- Rounded corners
- Text shadows, box shadows
- And so on…
Use the CSS tools at your disposal. They're resolution independent and bandwidth friendly!
Parting Thoughts
You don't need any of the aforementioned optimisations, they're optional!
From device pixel ratios and scaling to the zoom interaction method popularised by the iPhone, tweaks for high pixel density displays are simply a nice touch on what is becoming a very solid mobile web browsing experience.
Thanks for reading.
Comments
Comments, suggestions or feedback via Optic Swerve on Twitter please.
Almost every new client these days wants a mobile version of their website. It’s practically essential after all: one design for the BlackBerry, another for the iPhone, the iPad, netbook, Kindle — and all screen resolutions must be compatible, too. In the next five years, we’ll likely need to design for a number of additional inventions. When will the madness stop? It won’t, of course.
In the field of Web design and development, we’re quickly getting to the point of being unable to keep up with the endless new resolutions and devices. For many websites, creating a website version for each resolution and new device would be impossible, or at least impractical. Should we just suffer the consequences of losing visitors from one device, for the benefit of gaining visitors from another? Or is there another option?
Responsive Web design is the approach that suggests that design and development should respond to the user’s behavior and environment based on screen size, platform and orientation. The practice consists of a mix of flexible grids and layouts, images and an intelligent use of CSS media queries. As the user switches from their laptop to iPad, the website should automatically switch to accommodate for resolution, image size and scripting abilities. In other words, the website should have the technology to automatically respond to the user’s preferences. This would eliminate the need for a different design and development phase for each new gadget on the market.
The Concept Of Responsive Web Design
Ethan Marcotte wrote an introductory article about the approach, “Responsive Web Design,” for A List Apart. It stems from the notion of responsive architectural design, whereby a room or space automatically adjusts to the number and flow of people within it:
“Recently, an emergent discipline called “responsive architecture” has begun asking how physical spaces can respond to the presence of people passing through them. Through a combination of embedded robotics and tensile materials, architects are experimenting with art installations and wall structures that bend, flex, and expand as crowds approach them. Motion sensors can be paired with climate control systems to adjust a room’s temperature and ambient lighting as it fills with people. Companies have already produced “smart glass technology” that can automatically become opaque when a room’s occupants reach a certain density threshold, giving them an additional layer of privacy.”
Transplant this discipline onto Web design, and we have a similar yet whole new idea. Why should we create a custom Web design for each group of users; after all, architects don’t design a building for each group size and type that passes through it? Like responsive architecture, Web design should automatically adjust. It shouldn’t require countless custom-made solutions for each new category of users.
Obviously, we can’t use motion sensors and robotics to accomplish this the way a building would. Responsive Web design requires a more abstract way of thinking. However, some ideas are already being practiced: fluid layouts, media queries and scripts that can reformat Web pages and mark-up effortlessly (or automatically).
But responsive Web design is not only about adjustable screen resolutions and automatically resizable images, but rather about a whole new way of thinking about design. Let’s talk about all of these features, plus additional ideas in the making.
Adjusting Screen Resolution
With more devices come varying screen resolutions, definitions and orientations. New devices with new screen sizes are being developed every day, and each of these devices may be able to handle variations in size, functionality and even color. Some are in landscape, others in portrait, still others even completely square. As we know from the rising popularity of the iPhone, iPad and advanced smartphones, many new devices are able to switch from portrait to landscape at the user’s whim. How is one to design for these situations?
In addition to designing for both landscape and portrait (and enabling those orientations to possibly switch in an instant upon page load), we must consider the hundreds of different screen sizes. Yes, it is possible to group them into major categories, design for each of them, and make each design as flexible as necessary. But that can be overwhelming, and who knows what the usage figures will be in five years? Besides, many users do not maximize their browsers, which itself leaves far too much room for variety among screen sizes.
Morten Hjerde and a few of his colleagues identified statistics on about 400 devices sold between 2005 and 2008. Below are some of the most common:
Since then even more devices have come out. It’s obvious that we can’t keep creating custom solutions for each one. So, how do we deal with the situation?
Part of the Solution: Flexible Everything
A few years ago, when flexible layouts were almost a “luxury” for websites, the only things that were flexible in a design were the layout columns (structural elements) and the text. Images could easily break layouts, and even flexible structural elements broke a layout’s form when pushed enough. Flexible designs weren’t really that flexible; they could give or take a few hundred pixels, but they often couldn’t adjust from a large computer screen to a netbook.
Now we can make things more flexible. Images can be automatically adjusted, and we have workarounds so that layouts never break (although they may become squished and illegible in the process). While it’s not a complete fix, the solution gives us far more options. It’s perfect for devices that switch from portrait orientation to landscape in an instant or for when users switch from a large computer screen to an iPad.
In Ethan Marcotte’s article, he created a sample Web design that features this better flexible layout:
The entire design is a lovely mix of fluid grids, fluid images and smart mark-up where needed. Creating fluid grids is fairly common practice, and there are a number of techniques for creating fluid images:
For more information on creating fluid websites, be sure to look at the book “Flexible Web Design: Creating Liquid and Elastic Layouts with CSS” by Zoe Mickley Gillenwater, and download the sample chapter “Creating Flexible Images.” In addition, Zoe provides the following extensive list of tutorials, resources, inspiration and best practices on creating flexible grids and layouts: “Essential Resources for Creating Liquid and Elastic Layouts.”
While from a technical perspective this is all easily possible, it’s not just about plugging these features in and being done. Look at the logo in this design, for example:
If resized too small, the image would appear to be of low quality, but keeping the name of the website visible and not cropping it off was important. So, the image is divided into two: one (of the illustration) set as a background, to be cropped and to maintain its size, and the other (of the name) resized proportionally.
<h1 id="logo"><a href="#"><img src="site/logo.png" alt="The Baker Street Inquirer" /></a></h1>Above, the h1 element holds the illustration as a background, and the image is aligned according to the container’s background (the heading).
This is just one example of the kind of thinking that makes responsive Web design truly effective. But even with smart fixes like this, a layout can become too narrow or short to look right. In the logo example above (although it works), the ideal situation would be to not crop half of the illustration or to keep the logo from being so small that it becomes illegible and “floats” up.
Flexible Images
One major problem that needs to be solved with responsive Web design is working with images. There are a number of techniques to resize images proportionately, and many are easily done. The most popular option, noted in Ethan Marcotte’s article on fluid images but first experimented with by Richard Rutter, is to use CSS’s max-width for an easy fix.
img { max-width: 100%; }As long as no other width-based image styles override this rule, every image will load in its original size, unless the viewing area becomes narrower than the image’s original width. The maximum width of the image is set to 100% of the screen or browser width, so when that 100% becomes narrower, so does the image. Essentially, as Jason Grigsby noted, “The idea behind fluid images is that you deliver images at the maximum size they will be used at. You don’t declare the height and width in your code, but instead let the browser resize the images as needed while using CSS to guide their relative size”. It’s a great and simple technique to resize images beautifully.
Note that max-width is not supported in IE, but a good use of width: 100% would solve the problem neatly in an IE-specific style sheet. One more issue is that when an image is resized too small in some older browsers in Windows, the rendering isn’t as clear as it ought to be. There is a JavaScript to fix this issue, though, found in Ethan Marcotte’s article.
While the above is a great quick fix and good start to responsive images, image resolution and download times should be the primary considerations. While resizing an image for mobile devices can be very simple, if the original image size is meant for large devices, it could significantly slow download times and take up space unnecessarily.
Filament Group’s Responsive Images
This technique, presented by the Filament Group, takes this issue into consideration and not only resizes images proportionately, but shrinks image resolution on smaller devices, so very large images don’t waste space unnecessarily on small screens. Check out the demo page here.
This technique requires a few files, all of which are available on Github. First, a JavaScript file (rwd-images.js), the .htaccess file and an image file (rwd.gif). Then, we can use just a bit of HTML to reference both the larger and smaller resolution images: first, the small image, with an .r prefix to clarify that it should be responsive, and then a reference to the bigger image using data-fullsrc.
<img src="smallRes.jpg" data-fullsrc="largeRes.jpg">The data-fullsrc is a custom HTML5 attribute, defined in the files linked to above. For any screen that is wider than 480 pixels, the larger-resolution image (largeRes.jpg) will load; smaller screens wouldn’t need to load the bigger image, and so the smaller image (smallRes.jpg) will load.
The JavaScript file inserts a base element that allows the page to separate responsive images from others and redirects them as necessary. When the page loads, all files are rewritten to their original forms, and only the large or small images are loaded as necessary. With other techniques, all higher-resolution images would have had to be downloaded, even if the larger versions would never be used. Particularly for websites with a lot of images, this technique can be a great saver of bandwidth and loading time.
This technique is fully supported in modern browsers, such as IE8+, Safari, Chrome and Opera, as well as mobile devices that use these same browsers (iPad, iPhone, etc.). Older browsers and Firefox degrade nicely and still resize as one would expect of a responsive image, except that both resolutions are downloaded together, so the end benefit of saving space with this technique is void.
Stop iPhone Simulator Image Resizing
One nice thing about the iPhone and iPod Touch is that Web designs automatically rescale to fit the tiny screen. A full-sized design, unless specified otherwise, would just shrink proportionally for the tiny browser, with no need for scrolling or a mobile version. Then, the user could easily zoom in and out as necessary.
There was, however, one issue this simulator created. When responsive Web design took off, many noticed that images were still changing proportionally with the page even if they were specifically made for (or could otherwise fit) the tiny screen. This in turn scaled down text and other elements.
(Image: Think Vitamin | Website referenced: 8 Faces)Because this works only with Apple’s simulator, we can use an Apple-specific meta tag to fix the problem, placing it below the website’s <head> section. Thanks to Think Vitamin’s article on image resizing, we have the meta tag below:
<meta name="viewport" content="width=device-width; initial-scale=1.0">Setting the initial-scale to 1 overrides the default to resize images proportionally, while leaving them as is if their width is the same as the device’s width (in either portrait or lanscape mode). Apple’s documentation has a lot more information on the viewport meta tag.
Custom Layout Structure
For extreme size changes, we may want to change the layout altogether, either through a separate style sheet or, more efficiently, through a CSS media query. This does not have to be troublesome; most of the styles can remain the same, while specific style sheets can inherit these styles and move elements around with floats, widths, heights and so on.
For example, we could have one main style sheet (which would also be the default) that would define all of the main structural elements, such as #wrapper, #content, #sidebar, #nav, along with colors, backgrounds and typography. Default flexible widths and floats could also be defined.
If a style sheet made the layout too narrow, short, wide or tall, we could then detect that and switch to a new style sheet. This new child style sheet would adopt everything from the default style sheet and then just redefine the layout’s structure.
Here is the style.css (default) content:
/* Default styles that will carry to the child style sheet */ html,body{ background... font... color... } h1,h2,h3{} p, blockquote, pre, code, ol, ul{} /* Structural elements */ #wrapper{ width: 80%; margin: 0 auto; background: #fff; padding: 20px; } #content{ width: 54%; float: left; margin-right: 3%; } #sidebar-left{ width: 20%; float: left; margin-right: 3%; } #sidebar-right{ width: 20%; float: left; }Here is the mobile.css (child) content:
#wrapper{ width: 90%; } #content{ width: 100%; } #sidebar-left{ width: 100%; clear: both; /* Additional styling for our new layout */ border-top: 1px solid #ccc; margin-top: 20px; } #sidebar-right{ width: 100%; clear: both; /* Additional styling for our new layout */ border-top: 1px solid #ccc; margin-top: 20px; }
Media Queries
CSS3 supports all of the same media types as CSS 2.1, such as screen, print and handheld, but has added dozens of new media features, including max-width, device-width, orientation and color. New devices made after the release of CSS3 (such as the iPad and Android devices) will definitely support media features. So, calling a media query using CSS3 features to target these devices would work just fine, and it will be ignored if accessed by an older computer browser that does not support CSS3.
In Ethan Marcotte’s article, we see an example of a media query in action:
<link rel="stylesheet" type="text/css" media="screen and (max-device-width: 480px)" href="shetland.css" />This media query is fairly self-explanatory: if the browser displays this page on a screen (rather than print, etc.), and if the width of the screen (not necessarily the viewport) is 480 pixels or less, then load shetland.css.
New CSS3 features also include orientation (portrait vs. landscape), device-width, min-device-width and more. Look at “The Orientation Media Query” for more information on setting and restricting widths based on these media query features.
One can create multiple style sheets, as well as basic layout alterations defined to fit ranges of widths — even for landscape vs. portrait orientations. Be sure to look at the section of Ethan Marcotte’s article entitled “Meet the media query” for more examples and a more thorough explanation.
Multiple media queries can also be dropped right into a single style sheet, which is the most efficient option when used:
/* Smartphones (portrait and landscape) ----------- */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) { /* Styles */ } /* Smartphones (landscape) ----------- */ @media only screen and (min-width : 321px) { /* Styles */ } /* Smartphones (portrait) ----------- */ @media only screen and (max-width : 320px) { /* Styles */ }The code above is from a free template for multiple media queries between popular devices by Andy Clark. See the differences between this approach and including different style sheet files in the mark-up as shown in the post “Hardboiled CSS3 Media Queries.”
CSS3 Media Queries
Above are a few examples of how media queries, both from CSS 2.1 and CSS3 could work. Let’s now look at some specific how-to’s for using CSS3 media queries to create responsive Web designs. Many of these uses are relevant today, and all will definitely be usable in the near future.
The min-width and max-width properties do exactly what they suggest. The min-width property sets a minimum browser or screen width that a certain set of styles (or separate style sheet) would apply to. If anything is below this limit, the style sheet link or styles will be ignored. The max-width property does just the opposite. Anything above the maximum browser or screen width specified would not apply to the respective media query.
Note in the examples below that we’re using the syntax for media queries that could be used all in one style sheet. As mentioned above, the most efficient way to use media queries is to place them all in one CSS style sheet, with the rest of the styles for the website. This way, multiple requests don’t have to be made for multiple style sheets.
@media screen and (min-width: 600px) { .hereIsMyClass { width: 30%; float: right; } }The class specified in the media query above (hereIsMyClass) will work only if the browser or screen width is above 600 pixels. In other words, this media query will run only if the minimum width is 600 pixels (therefore, 600 pixels or wider).
@media screen and (max-width: 600px) { .aClassforSmallScreens { clear: both; font-size: 1.3em; } }Now, with the use of max-width, this media query will apply only to browser or screen widths with a maximum width of 600 pixels or narrower.
While the above min-width and max-width can apply to either screen size or browser width, sometimes we’d like a media query that is relevant to device width specifically. This means that even if a browser or other viewing area is minimized to something smaller, the media query would still apply to the size of the actual device. The min-device-width and max-device-width media query properties are great for targeting certain devices with set dimensions, without applying the same styles to other screen sizes in a browser that mimics the device’s size.
@media screen and (max-device-width: 480px) { .classForiPhoneDisplay { font-size: 1.2em; } }@media screen and (min-device-width: 768px) { .minimumiPadWidth { clear: both; margin-bottom: 2px solid #ccc; } }There are also other tricks with media queries to target specific devices. Thomas Maier has written two short snippets and explanations for targeting the iPhone and iPad only:
For the iPad specifically, there is also a media query property called orientation. The value can be either landscape (horizontal orientation) or portrait (vertical orientation).
@media screen and (orientation: landscape) { .iPadLandscape { width: 30%; float: right; } }@media screen and (orientation: portrait) { .iPadPortrait { clear: both; } }Unfortunately, this property works only on the iPad. When determining the orientation for the iPhone and other devices, the use of max-device-width and min-device-width should do the trick.
There are also many media queries that make sense when combined. For example, the min-width and max-width media queries are combined all the time to set a style specific to a certain range.
@media screen and (min-width: 800px) and (max-width: 1200px) { .classForaMediumScreen { background: #cc0000; width: 30%; float: right; } }The above code in this media query applies only to screen and browser widths between 800 and 1200 pixels. A good use of this technique is to show certain content or entire sidebars in a layout depending on how much horizontal space is available.
Some designers would also prefer to link to a separate style sheet for certain media queries, which is perfectly fine if the organizational benefits outweigh the efficiency lost. For devices that do not switch orientation or for screens whose browser width cannot be changed manually, using a separate style sheet should be fine.
You might want, for example, to place media queries all in one style sheet (as above) for devices like the iPad. Because such a device can switch from portrait to landscape in an instant, if these two media queries were placed in separate style sheets, the website would have to call each style sheet file every time the user switched orientations. Placing a media query for both the horizontal and vertical orientations of the iPad in the same style sheet file would be far more efficient.
Another example is a flexible design meant for a standard computer screen with a resizable browser. If the browser can be manually resized, placing all variable media queries in one style sheet would be best.
Nevertheless, organization can be key, and a designer may wish to define media queries in a standard HTML link tag:
<link rel="stylesheet" media="screen and (max-width: 600px)" href="small.css" /> <link rel="stylesheet" media="screen and (min-width: 600px)" href="large.css" /> <link rel="stylesheet" media="print" href="print.css" />JavaScript
Another method that can be used is JavaScript, especially as a back-up to devices that don’t support all of the CSS3 media query options. Fortunately, there is already a pre-made JavaScript library that makes older browsers (IE 5+, Firefox 1+, Safari 2) support CSS3 media queries. If you’re already using these queries, just grab a copy of the library, and include it in the mark-up: css3-mediaqueries.js.
In addition, below is a sample jQuery snippet that detects browser width and changes the style sheet accordingly — if one prefers a more hands-on approach:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(window).bind("resize", resizeWindow); function resizeWindow(e){ var newWindowWidth = $(window).width(); // If width width is below 600px, switch to the mobile stylesheet if(newWindowWidth < 600){ $("link[rel=stylesheet]").attr({href : "mobile.css"}); } // Else if width is above 600px, switch to the large stylesheet else if(newWindowWidth > 600){ $("link[rel=stylesheet]").attr({href : "style.css"}); } } }); </script>There are many solutions for pairing up JavaScript with CSS media queries. Remember that media queries are not an absolute answer, but rather are fantastic options for responsive Web design when it comes to pure CSS-based solutions. With the addition of JavaScript, we can accomodate far more variations. For detailed information on using JavaScript to mimic or work with media queries, look at “Combining Media Queries and JavaScript.”
Showing or Hiding Content
It is possible to shrink things proportionally and rearrange elements as necessary to make everything fit (reasonably well) as a screen gets smaller. It’s great that that’s possible, but making every piece of content from a large screen available on a smaller screen or mobile device isn’t always the best answer. We have best practices for mobile environments: simpler navigation, more focused content, lists or rows instead of multiple columns.
Responsive Web design shouldn’t be just about how to create a flexible layout on a wide range of platforms and screen sizes. It should also be about the user being able to pick and choose content. Fortunately, CSS has been allowing us to show and hide content with ease for years!
display: none;Either declare display: none for the HTML block element that needs to be hidden in a specific style sheet or detect the browser width and do it through JavaScript. In addition to hiding content on smaller screens, we can also hide content in our default style sheet (for bigger screens) that should be available only in mobile versions or on smaller devices. For example, as we hide major pieces of content, we could replace them with navigation to that content, or with a different navigation structure altogether.
Note that we haven’t used visibility: hidden here; this just hides the content (although it is still there), whereas the display property gets rid of it altogether. For smaller devices, there is no need to keep the mark-up on the page — it just takes up resources and might even cause unnecessary scrolling or break the layout.
Here is our mark-up:
<p class="sidebar-nav"><a href="#">Left Sidebar Content</a> | <a href="#">Right Sidebar Content</a></p> <div id="content"> <h2>Main Content</h2> </div> <div id="sidebar-left"> <h2>A Left Sidebar</h2> </div> <div id="sidebar-right"> <h2>A Right Sidebar</h2> </div>In our default style sheet below, we have hidden the links to the sidebar content. Because our screen is large enough, we can display this content on page load.
Here is the style.css (default) content:
#content{ width: 54%; float: left; margin-right: 3%; } #sidebar-left{ width: 20%; float: left; margin-right: 3%; } #sidebar-right{ width: 20%; float: left; } .sidebar-nav{display: none;}Now, we hide the two sidebars (below) and show the links to these pieces of content. As an alternative, the links could call to JavaScript to just cancel out the display: none when clicked, and the sidebars could be realigned in the CSS to float below the content (or in another reasonable way).
Here is the mobile.css (simpler) content:
#content{ width: 100%; } #sidebar-left{ display: none; } #sidebar-right{ display: none; } .sidebar-nav{display: inline;}With the ability to easily show and hide content, rearrange layout elements and automatically resize images, form elements and more, a design can be transformed to fit a huge variety of screen sizes and device types. As the screen gets smaller, rearrange elements to fit mobile guidelines; for example, use a script or alternate style sheet to increase white space or to replace image navigation sources on mobile devices for better usability (icons would be more beneficial on smaller screens).
Below are a couple of relevant resources:
Touchscreens vs. Cursors
Touchscreens are becoming increasingly popular. Assuming that smaller devices are more likely to be given touchscreen functionality is easy, but don’t be so quick. Right now touchscreens are mainly on smaller devices, but many laptops and desktops on the market also have touchscreen capability. For example, the HP Touchsmart tm2t is a basic touchscreen laptop with traditional keyboard and mouse that can transform into a tablet.
Touchscreens obviously come with different design guidelines than purely cursor-based interaction, and the two have different capabilities as well. Fortunately, making a design work for both doesn’t take a lot of effort. Touchscreens have no capability to display CSS hovers because there is no cursor; once the user touches the screen, they click. So, don’t rely on CSS hovers for link definition; they should be considered an additional feature only for cursor-based devices.
Look at the article “Designing for Touchscreen” for more ideas. Many of the design suggestions in it are best for touchscreens, but they would not necessarily impair cursor-based usability either. For example, sub-navigation on the right side of the page would be more user-friendly for touchscreen users, because most people are right-handed; they would therefore not bump or brush the navigation accidentally when holding the device in their left hand. This would make no difference to cursor users, so we might as well follow the touchscreen design guideline in this instance. Many more guidelines of this kind can be drawn from touchscreen-based usability.
A Showcase Of Responsive Web Design
Below we have a few examples of responsive Web design in practice today. For many of these websites, there is more variation in structure and style than is shown in the pairs of screenshots provided. Many have several solutions for a variety of browsers, and some even adjust elements dynamically in size without the need for specific browser dimensions. Visit each of these, and adjust your browser size or change devices to see them in action.
Art Equals Work
Art Equals Work is a simple yet great example of responsive Web design. The first screenshot below is the view from a standard computer screen dimension. The website is flexible with browser widths by traditional standars, but once the browser gets too narrow or is otherwise switched to a device with a smaller screen, then the layout switches to a more readable and user-friendly format. The sidebar disappears, navigation goes to the top, and text is enlarged for easy and simple vertical reading.Think Vitamin
With Think Vitamin, we see a similar approach. When on a smaller screen or browser, the sidebar and top bar are removed, the navigation simplifies and moves directly above the content, as does the logo. The logo keeps its general look yet is modified for a more vertical orientation, with the tagline below the main icon. The white space around the content on larger screens is also more spacious and interesting, whereas it is simplified for practical purposes on smaller screens.8 Faces
8 Faces’ website design is flexible, right down to a standard netbook or tablet device, and expands in content quantity and layout width when viewed on wider screens or expanded browsers. When viewed on narrower screens, the featured issue on the right is cut out, and the content below is shortened and rearranged in layout, leaving only the essential information.Hicksdesign
The Hicksdesign website has three columns when viewed on a conventional computer screen with a maximized browser. When minimized in width, the design takes on a new layout: the third column to the right is rearranged above the second, and the logo moves next to the introductory text. Thus, no content needs to be removed for the smaller size. For even narrower screens and browser widths, the side content is removed completely and a simplified version is moved up top. Finally, the font size changes with the screen and browser width; as the browser gets narrower, the font size throughout gets smaller and remains proportional.Information Architects
Here is a great example of a flexible image. The image in this design automatically resizes after certain “break” points, but in between those width changes, only the side margins and excess white space are altered. On smaller screens and minimized browsers, the navigation simplifies and the columns of navigation at the top fall off. At the design’s smallest version, the navigation simplifies to just a drop-down menu, perfect for saving space without sacrificing critical navigation links.Garret Keizer
The website for Garret Keizer is fully flexible in wider browsers and on larger screens: the photo, logo and other images resize proportionally, as do the headings and block areas for text. At a few points, some pieces of text change in font size and get smaller as the screen or browser gets narrower. After a certain break point, the layout transforms into what we see in the second screenshot below, with a simple logo, introductory text and a simple vertical structure for the remaining content.Simon Collison
With four relatively content-heavy columns, it’s easy to see how the content here could easily be squished when viewed on smaller devices. Because of the easy organized columns, though, we can also collapse them quite simply when needed, and we can stack them vertically when the space doesn’t allow for a reasonable horizontal span. When the browser is minimized or the user is on a smaller device, the columns first collapse into two and then into one. Likewise, the horizontal lines for break points also change in width, without changing the size or style of each line’s title text.CSS Tricks
On the CSS Tricks website, like many other collapsible Web designs, the sidebars with excess content are the first to fall off when the screen or browser gets too narrow. On this particular website, the middle column or first sidebar to the left was the first to disappear; and the sidebar with the ads and website extras did the same when the browser got even narrower. Eventually, the design leaves the posts, uses less white space around the navigation and logo and moves the search bar to below the navigation. The remaining layout and design is as flexible as can be because of its simplicity.Tee Gallery
As one can see, the main navigation here is the simple layout of t-shirt designs, spanning both vertically and horizontally across the screen. As the browser or screen gets smaller, the columns collapse and move below. This happens at each break point when the layout is stressed, but in between the break points, the images just change proportionally in size. This maintains balance in the design, while ensuring that any images (which are essential to the website) don’t get so small that they become unusable.City Crawlers: Berlin
When varied between larger screen sizes and browser widths, this design remains flexible. It also remains flexible after a few layout pieces collapse into a more vertical orientation for small screens and narrow browsers. At first, the introductory image, logo and navigation image links resize proportionally to accommodate variations in screen and browser widths, as do the blocks of content below. The bottom columns of content eventually collapse and rearrange above or below other pieces, until (at the narrowest point) they are all stacked vertically. In the layout for the smallest screen and narrowest browser, the slideshow is left out altogether, the navigation is moved below the logo and other images are also removed.Ten by Twenty
Ten by Twenty is another design that does not resort to changing layout structure at all after certain break points, but rather simplifies responsive Web design by making everything fully flexible and automatically resizing, no matter what the screen or browser width. After a while, the design does stress a bit and could benefit from some rearrangement of content. But overall, the image resizing and flexible content spaces allow for a fairly simple solution that accommodates a wide range of screen sizes.Hardboiled Web Design
On wide screens and browsers, all of the content on this simply designed website is well organized into columns, sidebar and simple navigation up top. It’s a fairly standard and efficient layout. On smaller screens, the sidebar is the first to drop off, and its content is moved below the book previews and essential information. Being limited in space, this design preserves its important hierarchy. Whereas on a wider screen we’d look left to right, on a narrower screen we’d tend to look from top to bottom. Content on the right is moved below content that would appear on the left on a wider screen. Eventually, when the horizontal space is fully limited, the navigation is simplified and stacked vertically, and some repeated or inessential elements are removed.Teixido
This design features a complex layout that looks inspired by a print style. When viewed on a standard wide computer screen, more portfolio pieces are featured and spanned horizontally across the page. As one moves down the page, more graphics and imagery span the space. On a smaller screen, the portfolio piece is cut down to one, and then eventually left out altogether for very small screens and narrow browsers. The visualizations below collapse into fewer columns and more rows, and again, some drop off entirely for very small screens. This design shows a creative and intelligent way to make a not-so-common layout work responsively.Stephen Caver
This design has three main stages at which the design and layout collapse into a more user-friendly form, depending on how wide the screen or browser is. The main image (featuring type) is scaled proportionally via a flexible image method. Each “layout structure” is fully flexible until it reaches a breaking point, at which point the layout switches to something more usable with less horizontal space. The bottom four columns eventually collapse into two, the logo moves above the navigation, and the columns of navigation below are moved on top or below each other. At the design’s narrowest stage, the navigation is super-simplified, and some inessential content is cut out altogether.Unstoppable Robot Ninja
This layout does not change at all; no content is dropped or rearranged; and the text size does not change either. Instead, this design keeps its original form, no matter what the change in horizontal and vertical space. Instead, it automatically resizes the header image and the images for the navigation. The white space, margins and padding are also flexible, giving more room as the design expands and shrinks.Bureau
This is perhaps the simplest example of a responsive Web design in this showcase, but also one of the most versatile. The only piece in the layout that changes with the browser width is the blog post’s date, which moves above the post’s title or to the side, depending on how much horizontal space is available. Beyond this, the only thing that changes is the width of the content area and the margin space on the left and right. Everything is centered, so a sense of balance is maintained whatever the screen or browser width. Because of this design’s simplicity, switching between browser and screen widths is quick and easy.CSS Wizardry
Harry Roberts shows that responsive design can also have quite humble uses. If the user has a large viewport, the website displays three columns with a navigation menu floating on the left. For users with a viewport between 481px and 800px, a narrow version is displayed: the navigation jumps to the top of the site leaving the area for the content column and the sidebar. Finally, the iPhone view displays the sidebar under the content area. Harry also wrote a detailed article about the CSS styles he added to the stylesheet in his article “Media queries, handier than you think“. A nice example of how a couple of simple CSS adjustments can improve the website’s appearance across various devices.Bryan James
This last design by Bryan James shows that responsive Web design need not apply only to static HTML and CSS websites. Done in Flash, this one features a full-sized background image and is flexible up to a certain width and height. As a result of the design style, on screens that are too small, the background image gets mostly hidden and the content can become illegible and squished. Instead of just letting it be, though, a message pops up informing the user that the screen is too small to adequately view the website. It then prompts the user to switch to a bigger screen. One can discuss if the design solution is good or bad in terms of usability, but the example shows that Flash websites can respond to user’s viewport, too.Conclusion
We are indeed entering a new age of Web design and development. Far too many options are available now, and there will be far too many in the future to continue adjusting and creating custom solutions for each screen size, device and advancement in technology. We should rather start a new era today: creating websites that are future-ready right now. Understanding how to make a design responsive to the user doesn’t require too much learning, and it can definitely be a lot less stressful and more productive than learning how to design and code properly for every single device available.
Responsive Web design and the techniques discussed above are not the final answer to the ever-changing mobile world. Responsive Web design is a mere concept that when implemented correctly can improve the user experience, but not completely solve it for every user, device and platform. We will need to constantly work with new devices, resolutions and technologies to continually improve the user experience as technology evolves in the coming years.
Besides saving us from frustration, responsive Web design is also best for the user. Every custom solution makes for a better user experience. With responsive Web design, we can create custom solutions for a wider range of users, on a wider range of devices. A website can be tailored as well for someone on an old laptop or device as it can for the vast majority of people on the trendiest gadgets around, and likewise as much for the few users who own the most advanced gadgets now and in the years to come. Responsive Web design creates a great custom experience for everyone. As Web designers, we all strive for that every day on every project anyway, right?
Further Resources
(al) (vf)
Responsive IMGs Part 2 — In-depth Look at Techniques
In Responsive IMGs Part 1, I took a high-level look at what responsive IMGs are, the problem they are trying to solve, and the common issues they face. In this post, I’m going to take a deeper look at the specific techniques being used to provide responsive IMGs and try to evaluate what works and doesn’t. If you haven’t read part 1, you may want to do so before reading this post as it will help explain some of the terms I use.
When I started working on this project two months ago, I thought I would get to the end and be able to say, “Here are the three approaches that work best. Go download them and figure out how to integrate them into your systems.” Oh naivety!
What I’ve found is that there is no comprehensive solution. Instead, we have several months of experiments. Each experiment has its own advantages and disadvantages.
Because of this, the best thing we can do is understand the common elements and challenges so that we can start to pick the best parts of each for building our own solutions.
So um… this is a long post. Sorry. :-)
Abandoned approaches
Dynamic Base Tag
Many of the early techniques used javascript to dynamically change the base tag. The new base tag would add directories into the path that would be used to indicate what size image should be retrieved. After the document loaded, the base tag would be removed.
Unfortunately, this approach ran into race conditions that I described in part 1. I found that Google Chrome was downloading both the mobile and desktop images. Scott Jehl found the problem to be a difference between how inline and external javascript is handled. He submitted a bug to webkit which has been marked as “won’t fix” because:
Inserting base element effectively changes all the subsequent URLs on the page. Any script may insert one so to avoid double loads we could never load anything else as long as there is a pending script load. This would mean disabling preloading, which is out of the question.
In theory, you could still use a dynamic base tag inline, but the Filament Group has been primarily using a cookies-based approach instead which seems safer.
Temporary images
Another early technique was to have the src of imgs pointing to a temporary image and then having javascript replace the source with the correct file path. In most cases, the image was an one pixel transparent gif set up with caching which would hopefully prevent the browser from requesting it more than once no matter how many times it was referenced in the page.
The problem with this technique is that if javascript isn’t present, the browser will never download the images.
Javascript-based solutions
Where do you store the path to alternate versions of an image?
If the the img points to ‘small.jpg’, where do you put the information that ‘large.jpg’ is what should be loaded on larger screens?
URL parameters
One solution is to put the path to alternate versions of the image in the src attribute as url parameters. In its simplest form:
<img src="small.jpg?full=large.jpg">
If you have multiple sizes of images, they simply get added as additional values on the url. The key to making this work is coupling it with an .htaccess file.
Potential CDN, proxies, and caching issues
The big drawback to using URL parameters is that it may cause problems with content deliver networks and proxies that doesn’t pay attention to url parameters when caching content. Some caching algorithms ignore anything that has a URL parameter on it which means that pages will slow down because images aren’t cached.
Others will simply cache the first version of the image they see. If the first person behind a proxy cache happened to view the page on a mobile phone, then every subsequent user sees the mobile size image until the cache expires.
How likely is this to be an issue? I had the same question so I asked Steve Souders. He says that it is enough of a problem that you can’t ignore it. This echoes comments by Bryan and Stephanie Rieger at Breaking Development about problems with caching and CDNs.
Therefore, I think we should be looking for techniques that don’t use url parameters.
Examples of this approach:
Data attributes
Instead of putting the file path into the url parameters, the information is put in one or more data- attributes. For example:
<img src=”small.r.jpg” data-fullsrc=”large.jpg”>
Which element has data attributes added to it and how many are added depends on the technique.
Looping through every img tag
The only disadvantage to this technique that I’m aware of is the fact that the javascript has to loop through every image, check for data attributes, and then modify the src attribute depending on screen size. This is probably not a big problem on desktop browsers which is where the loop is mostly to be used.
Examples of this approach
Assumed file structure
In this variation, the file path isn’t included in the HTML document. Instead, it is assumed that the images are put on the server in a regular fashion. For example, all small images might be in /images/sml/ whereas large images are in /images/lrg/.
If this is true, then the html doesn’t need to provide both paths. It just needs to provide the image filename (e.g., boat.jpg) and then let javascript modify the src to be appropriate for the size of the screen (/images/lrg/boat.jpg for desktop).
Examples of this approach
Dynamic file names
One of the things that I suggested in part 1 was that we might need arbitrary image sizes. Some of the solutions are built around the assumption that you can pass the dimensions that you want in the url and get back an image at that size.
Because the images are resized on the fly, there is no need to store alternative file paths in the HTML document. Javascript will modify the filename from something like ‘boat.jpg’ to ‘boat-480×200.jpg’. There is no issue with caching or CDNs because each image is unique.
Some images cannot simply be resized
This approach doesn’t provide a good solution for manually choosing images at different sizes. It assumes that resizing images will work in all cases which we know is not true.
Examples of this approach
Role of .htaccess (or similar rewrite rules)
Many of the solutions rely on server rewrite rules. The examples are usually written using Apache .htaccess files, but they could be any sort of rewrite rule.
Lets look at a snippet of the .htaccess file from Responsive Images JS cookie-based branch to see how rewrite rules are being used:
RewriteEngine On #large cookie, large image RewriteCond %{HTTP_COOKIE} rwd-screensize=large RewriteCond %{QUERY_STRING} large=([^&]+) RewriteRule .* %1 [L]
The first line turns rewrite rules on. Next comes a couple of conditions (RewriteCond). The first checks to see if there is a cookie called rwd-screensize that has the value of large. The second checks to see if the query string for the url contains a value for large. This .htaccess file is looking for something like:
<img src="small.jpg?large=large.jpg">
If both conditions are met—the cookie is set to large and there is a large value in the query string—then the rewrite rule will send the file that was specified in the query string (in the example above, that would be large.jpg).
The rwd-screensize cookie is set by javascript after it tests for the screen size.
How do you prevent the browser from downloading multiple images?
With the basics out of the way, we can now get to the tricky part. As mentioned in part 1, intercepting the browser before it starts downloading images so that you can evaluate and possibly change the source of those images is tricky and may result in race conditions.
Now that the dynamic base tag has been ruled out, there are two main techniques that remain.
Set a cookie
This is the method that the Filament Group settled on for the Boston Globe. Javascript is inserted into the head of the document so that it evaluates as soon as possible.
After it determines the screen size, it sets a cookie. Every subsequent image request sent from the browser will include the cookie. The server can use the cookie to determine the best image to sent back to the user.
Potential problems
If the browser doesn’t support cookies or the user blocks them, then the javascript will have no effect.
Also, Yoav Weiss has done some testing and shared results that indicate that duplicate files will be downloaded by IE9. Firefox will download duplicate files if the script is external, but not if it internal. This suggests that cookies may also be subject to the race condition problem that caused us to abandon the dynamic base tag approach.
Examples of this approach
Noscript tag
Within the last couple of months, new techniques have emerged that use the noscript tag as a way to prevent extra downloads. The first post I saw describing this technique was by Mairead Buchan. She describe it as having “ the elegance of a wading hippo”. Despite that description, I think this technique holds promise.
A cleaner implementation of the noscript approach was created independently by Antti Peisa. Here is the html:
<noscript data-large='Koala.jpg' data-small='Koala-small.jpg' data-alt='Koala'> <img src='Koala.jpg' alt='Koala' /> </noscript>
The values for the various sizes of image tags are stored in the data attributes on the noscript tag itself. Antti then provides sample jQuery code used to process the image:
$('noscript[data-large][data-small]').each(function(){ var src = screen.width >= 500 ? $(this).data('large') : $(this).data('small'); $('<img src="' + src + '" alt="' + $(this).data('alt') + '" />').insertAfter($(this)); });
These lines go through the document to find noscript tags with the appropriate data attributes. It tests for the screen size and then inserts a new img tag with the appropriate image path and alt tag.
No race conditions!
When using the noscript tag, there are no rendering race conditions. The image in the noscript tag never starts downloading. Mairead explained that “it works because children of the <noscript> tag are not added to the DOM”.
This makes sense. The browser knows if javascript is available before it starts rendering a page. If javascript is available, there is no reason to worry about doing anything with items inside the noscript tag. If they aren’t getting added to the DOM, they certainly aren’t going to get downloaded.
This technique also has fallbacks if javascript isn’t enabled and doesn’t rely on cookies or htaccess files.
Potential gotchas
The biggest gotcha will be devices that profess to support javascript, but have poor implementations. For example, Blackberry 4.5 has javascript, but javascript cannot manipulate the DOM. Ergo, the noscript tag will not get used because scripts are available, but the script won’t successfully add a new img tag so no images will show.
Please note, this is speculation on my part. I know how Blackberry 4.5 behaves, but I haven’t tested this particular approach on a 4.5 device.
Even though this approach does not create a race condition, it is important that the javascript execute as quickly as possible. Inserting all of these images may require the browser to reflow the page. It also may cause the browser to load assets less efficiently because it cannot start prefetching assets.
Because of the need to execute as quickly as possible, it makes sense to remove the jQuery dependency from Antti’s javascript and put the code in the head of the document.
Examples of this approach
Is screen size the right thing to look at?
Most of these techniques rely on the size of the screen to determine what the image size should be. Andy Hume points out that the size of the screen may be misleading. He writes:
The content driven approach to fixing this is to decide which image to load based on whether the image will be stretched beyond its true pixel width. If you stretch an image beyond its true width it begins to look pixelated or blurry. In this scenario, we want to load in a higher resolution version of the image.
Andy’s fork of the Responsive Images JS tackles this problem (and adds support for nginx).
Boston Globe Responsive IMGs are Busted
I’ve been looking forward to the Boston Globe’s launch for quite some time. It is a tremendous feat of engineering and design. It has the volume of traffic necessary to test different approaches to responsive IMGs and see what works and what doesn’t.
The technique that they chose to use combines data attributes with cookies. Unfortunately, responsive IMGs are currently broken on the Boston Globe site. This is a known problem and they are working on fixing it.
The upshot is that we don’t yet have a large scale deployment of any of these techniques that we can interrogate and point to as validation that a particular combination is battle-hardened.
Most promising javascript only techniques
In my mind, cookies plus data-src and noscript are the two most promising techniques. Both have problems, but they have far fewer gotchas than other approaches.
Server side solutions
Most of the javascript techniques require little, if any, support from the server. There are alternate approaches that leverage the server for a bunch of the heavy lifting.
User agent string parsing
A few people have demonstrated solutions that do light-weight user agent string parsing to identify various mobile phones. If the user agent can be identified as iPhone or Android, then declare the device mobile and set the image size appropriately.
Unlike a lot of developers, I don’t have a problem with device detection based on user agent string. But if you’re going to start doing it for mobile, you have to take on real device detection via WURFL, Device Atlas, etc. Simplistic regular expression matching and assumptions about screen sizes isn’t going to work.
Device detection
There are a couple of different approaches that rely on device detection to determine the screen size and deliver an appropriate image back. Device detection databases are pretty good about having basic information like screen size.
Sencha.io Src (formerly called TinySRC)
James Pearce created a fantastic service called TinySRC. He later went to work for Sencha and TinySRC became Sencha.io Src. Sencha.io Src automatically resizes images for you. You reference Sencha.io Src in your img stag like this:
http://src.sencha.io/http://www.myapp.com/myimg.jpg
When a browser requests the url above, Sencha.io Src will look up the user agent of the device making the request to determine what size image is appropriate. It will then grab the image from your server and resize it. It then caches the resized image so that subsequent requests can be served quickly.
In addition to the automatic mode, Sencha.io Src will also allow you to specify specific sizes that you would like the image resized to.
Combining Responsive Images JS with Sencha.io Src
Andrea Trasatti forked Scott Jehl’s Responsive Images JS to combine responsive IMGs with TinySRC. The script finds the screen size using javascript and then uses htaccess to request the image at the correct size from Sencha.io Src.
Andrea’s version was written fairly early. It still uses dynamic base tags, url parameters, and results in “1 HTTP request for every image that we might avoid”. But all of these problems could be remedied by combining what Andrea started with some of the newer approaches.
Potential drawbacks
First, if you have a religious aversion to device detection, then you probably don’t want to use Sencha.io Src or you need to use it in a scenario where can specify the image size that you want.
As an aside, I’ve found it funny to see people who speak ill of device detection and user agent strings suggest that people use TinySRC. I once saw a slide deck that dismissed device detection and then a couple of slides later talked about how great TinySRC is. If only they knew. :-)
On a more practical level, you have to evaluate whether or not the service will remain up and what happens if all of your content points to sencha urls that suddenly go away. I don’t think Sencha is going to go anywhere anytime soon. I know James well enough to know he’ll want to keep this service running forever if he can. But even all that said, looking at the long term availability of a service is something that needs to be considered.
WURFL-based solution
WURFL is the largest open source device database. After attending the Breaking Development conference earlier this month, Carson McDonald was inspired to develop a WURFL-based solution for images. It’s awesome to see something come together so quickly after the conference.
(BTW, Breaking Development is the best conference in North America for web on mobile. Registration for the next event opens today. You should attend!)
Carson notes that his approach will likely have the same problems with CDNs and caching because different size images come from the same url.
Image resizing services
Google’s mod_pagespeed
Google’s mod_pagespeed Apache module automates many performance tasks and includes an option to scale any images on the fly. There are many ways to scale images (GD, ImageMagick, etc.). I decided to call out mod_pagespeed because it was one I hadn’t considered until I saw it suggested in a forum. I don’t know of anyone who has explored how it might be used in an responsive IMGs solutions.
Combining client and server approaches
Adaptive Images
As you can probably tell by now, there are few solutions that you can simply install and forgot about. Most require at minimum changes to the way you mark up the page. The two solutions that come closest to be plug and play are Sencha.io Src and Adaptive-Images.com.
Adaptive images was developed by Matt Wilcox. It turns the premise of Responsive IMGs on its head by assuming that the markup on the page will contain the large versions of images and will not start with the mobile versions.
The solution consists of three pieces:
1. A small snippet of javascript placed in the head that sets a cookie with the screen width and height.
<script>document.cookie='resolution='+Math.max(screen.width,screen.height)+'; path=/';</script>
2. A .htaccess that rewrites all requests for images to a php file. You declare directories that you want to exempt from this rewrite. For example, you don’t want your media query savvy CSS background images getting routed through the php file.
3. The php file which resizes the image based on breakpoints that you can configure.
The best part of Matt’s solution is that as long as you can separate out your image files so you can exclude ones that shouldn’t be resized, you can implement this technique without making any changes to your existing markup. Existing pages and posts will suddenly have different image sizes.
And now for the problems
Come on, by now you weren’t expecting it to be that simple did you?
Because the images start with the large size, if javascript is not available, the large size will be delivered. The most common devices to not have javascript support are older feature phones. The type of devices that will choke and even crash on large images are older feature phones.
This technique also suffers from the same race conditions that most of the javascript solutions do. The cookie has to be set early to avoid extra downloads.
Update: Matt commented below and points out that the default settings will result in a small image being delivered if javascript isn’t present. The markup will point to a large version, but the php file returns a small version. All of this is configurable.
Also, he is right that the result of the race condition would not be multiple downloads. I think the race condition still exists with different drawbacks, but I’m going continue the conversation in the comments where Matt and I can converse.
I also missed the fact that the url will stay the same regardless of the size of image which can cause issues with CDNs and proxy caching as noted earlier.
Yiibu profile approach
Brian and Stephanie Rieger presented the work they did for browser.nokia.com at Breaking Development conference. For that project, they invented a new way to combine client side information with device detection.
When a browser first requests something from the server, they don’t know anything about the device. So they check with a device detection database to see what they can find out about the size of the screen (and other details). They then check their own local database of tacit knowledge. This a database of things they’ve learned about how specific browsers work and any overrides they want to use. They use the combination of this information to deliver the appropriate HTML, javascript and images.
Once the browser gets this information, a javascript runs that tests the various aspects of the browser including screen size. It then stores this information in a profile cookie.
On the second request, the server receives the profile cookie and compares it to the information it has in its tacit database. It may update the tacit database. It combines the information into a revised profile combining server side information with client feature detection data.
I’m likely doing a poor job of describing the solution. Your best bet is to look at their slides:
This combined technique mitigates the problem of first load without any of the race conditions or potential problems that the client-only solutions have. It also extends beyond images to other content and javascript.
Sounds great. What’s the catch?
It is a complex system and requires significant changes to infrastructure to support. Bryan and Stephanie have published the approach, but the code isn’t available for download. It may be coming, but they took a well-deserved vacation after spending most of the summer working on the Nokia Browser project.
Probably the biggest problem with this approach is that most of us are not the Riegers. They have been doing mobile web for years. Their tacit knowledge of devices is exceptional. Freaking geniuses. That’s hard to replicate.
The same is true of the Boston Globe project. The team working on that included significant portions of the jQuery Mobile team and the guy who coined the phrase responsive web design. Few of us are going to be so lucky on our next project. :-)
Summary
As I’ve reviewed the various techniques, I keep thinking back to something Andy Hume said in response to part 1:
Our current solutions are hugely dependant on the current (and undefined) behaviour of browsers in regard to the page-load race conditions you mention. For example, most responsive image implementations would be compromised if a particular type of look-ahead pre-parser (http://goo.gl/TyzTi) began to speculatively download images before actually parsing the HTML or executing any script. (I half expect us to get bitten by this any day.) One way or the other we need to consort with browser makers to get future-friendly.
That’s the truth of it. Most of these techniques are based on our hope that browsers continue to download assets in the order we have observed to date. If the the order changes or if browsers start pre-parsing more aggressively, the whole house of cards may fall down.
In part 3 of this series, I’m going to look at the conversations going on about ways to change the img tag or replace it with something that will work better with multiple file sources.
Sources and Acknowledgments
I reviewed 18 different techniques for this post. My notes are captured in a Google spreadsheet that you are welcome to review for detailed comments on each library. Thanks to everyone for publishing their thoughts and experiments. I learned a lot from each one.
This series wouldn’t have been possible without the assistance of Scott Jehl and Bryan and Stephanie Rieger. Scott in particular helped me sort out the problems with the main Responsive Images JS library. Thanks to all three of you for putting up with my many naive questions and for taking the time to explain all of the work you’ve been doing!
Responsive IMGs — Part 1
In my post “Where are the Mobile First Responsive Web Designs”, I noted that one of the first things I look for when trying to determine whether or not a responsive web design is “mobile first” is whether or not it has a strategy for handling the IMG tag.
A recent Smashing Magazine round up of responsive web design techniques included several new approaches for handling IMG tags which makes it the perfect time to dig into this problem and the potential solutions in more depth.
Why IMG Tags Suck for Responsive Web Design
If you want your site to load as quickly as possible, you do want to deliver larger files than are needed. Many responsive web design sites provide mobile devices images at sizes appropriate for desktop and ask the mobile device to resize the image.
In my research, I found nearly 80% decrease in file size by delivering images at the actual size they were going to be used on a mobile device.
So what’s the problem with the IMG element in responsive designs? Unlike CSS images which can provide different source files based on screen resolution using media queries, IMGs have a single source attribute.
What are Responsive IMGs?
Responsive IMGs are images delivered using the HTML IMG tag that come from different sources depending the screen size. There are many different techniques for accomplishing Responsive IMGs.
As far as I can tell, Scott Jehl first coined the phrase Responsive Images to describe a javascript solution to the img source problem. He also referred to Responsive IMGs as a general term recently so I’m hopeful he doesn’t mind the fact that I’m extending his definition to describe any technique that attempts to provide images at an appropriate size for a responsive design.
Responsive IMGs Challenges
There are some common challenges that any Responsive IMG technique will face. As we review the various techniques that have been proposed, we need to keep these challenges in mind.
Minimum Bar: Start with Mobile, No Extra Downloads
Scott Jehl set a minimum bar for Responsive IMGs by stating they must do the following:
- Start with mobile img
- Upgrade to larger size without downloading both
Both of these are worthy and necessary goals.
The First Page Load Problem
Any solution that relies on client-side scripting to make a decision about what image source to display will suffer from a first page load problem. The first time someone visits a site, the server won’t know what size image to provide.
Image from Bryan Rieger’s Muddling Through the Mobile Web presentation, photo by wscullin, licensed under Creative Commons.
If javascript is added that determines what image size is appropriate, then this information can be retained for the user session via cookies or similar techniques. In theory, on subsequent requests the server can make a decision about what size image to include in IMG tag.
FWIW, the speed of first load is a big deal. The speed of a person’s first experience can dictate their impression of a product and company. Google, Yahoo and others have talked about how minor speed differences makes a big difference in usage of their products.
Rendering Race Conditions
Techniques that rely on adjusting the image source attribute via javascript need to make sure that the modification happens before the image requests start.
Browser makers have done a lot of work to download as many assets as possible at the same time. Usually this is a good thing. But in the case of responsive imgs, the javascript needs to evaluate what size image to retrieve before any image requests start.
A lot of earlier work was done using dynamic base tags. This worked when the javascript was inline in the head tag, but failed to prevent images from downloading twice when an external javascript file is used.
The upshot is that nearly every client side technique requires deep understanding of the order in which different browsers process and download assets. Or more realistically, each approach needs to be tested extensively.
Content Delivery Networks and Caching
When you deliver different size images at the same url, you can run into problems with CDNs and other caching at the edge of the network. If the first person to request an image is on a mobile phone, people who follow via the same CDN or cache will also see the mobile-optimized image even if they are on desktop unless consider CDNs in your strategy.
Future Friendly Responsive IMGs
If we accept that the “quantity and diversity of connected devices—many of which we haven’t imagined yet—will explode”, then we need to consider look for solutions that are future friendly. In addition to the current experimentation, we need to start thinking about what a long term solution might look like.
For example, many of the early solutions for Responsive IMGs consist of two size images: one for desktop and one for mobile screen sizes. Will two image sizes really suffice for all of the devices that are coming?
Also, a lot of the solutions right now tackle one part of the problem. They may tackle the client side changes to switch the image source, but leave as an exercise for the developer to figure out how image resizing will be handled. For shared libraries, limited scope makes sense.
But as we look at what systems will need to do to be successful in the future, we need to think about what we want out of both the server and client side.
Here are some of the things that I think a future friendly technique will need to consider:
- Support arbitrary image resizing — We cannot anticipate what screen sizes may be coming. We need systems that handle image resizing automatically and support any arbitrary size needed for a particular page.
- Art direction can override automatic resizing — Not every image can be resized without losing the meaning of the image. Sometimes cropping an image may work better than resizing it. Automatic tools need to easily support manual override.
- Support for higher resolution displays — What do we do with the iPhone 4’s retina display and other devices sharing similar high resolution screens? It is an open question about whether we should deliver higher resolution images to those devices given the performance hit that will occur if the person is on a slow connection.
But regardless of how we chose to handle it right now, it is clear that the trend towards more pixels per inch on displays is not going away. If anything, we’re seeing indicators that higher density will soon be available on desktop displays as well.This means that our current definition of what is a large image for web is probably too small for future devices. With that in mind, it probably makes sense for systems to accept the highest resolution image possible—even if that resolution isn’t currently being used—so that when new devices become available the high resolution source is already available and hasn’t been lost.
- Connection speed should be part of the criteria — We can be much smarter about the size of the image we deliver if we can tell something about the network connection. We need an easier way to get at this information.
- A replacement for the IMG tag? — All of the responsive image solutions are attempting to deal with the fact that the image tag has only a single source. There have been various proposals recently to take a new look at what the tag should be and see if we can find a long term replacement.
That’s my short list. What would you add?
In part 2, I’ll take a closer look at the current alternatives for responsive imgs and which ones hold the most promise.
Back in January, we published an article on responsive design, “Responsive Web Design: What It Is and How to Use It.” Responsive design continues to get a lot of attention, but considering how different it is from the “traditional” way of designing websites, it can be a bit overwhelming for those designers who have yet to try it.
To that end, we’ve compiled this round-up of resources for creating responsive website designs. Included are tutorials, techniques, articles, tools and more, all geared toward giving you the specific knowledge you need to create your own responsive designs.
Responsive Design Techniques
CSS Transitions and Media Queries
Elliot Jay Stocks provides insight into the combination of CSS media queries and CSS transitions. The basic premise is this: you use media queries to design responsive websites that adapt in layout according to browser width, and you constantly resize your browser to see how the website performs, but every time a query kicks in, there’s a harsh jump between the first style and the second. Why not use some simple CSS transitions to smooth the jump by animating the resize? A nice case study.Responsive Data Tables
Chris Coyier and Scott Jehl are experimenting with responsive design techniques for displaying data tables. By default, data tables can be quite wide, and necessarily so. You could zoom out and see the whole table, but then the text size would be too small to read. You could zoom in to make it readable, but then you’d have to scroll both vertically and horizontally (sad face) to browse the table. One solution is to reformat the table for better readability. Another is to display a pie graph from the data. Yet another is to adapt the table into a mini-graphic for narrow screens (rather than interfering much with the content when the full table is displayed).Responsive Navigation Menus: Convert a Menu to a Dropdown for Small Screens
Chris Coyier describes another technique for converting a regular row of links into a dropdown menu when the browser window is narrow. When the user is on a small screen and clicks the dropdown, they’ll get an interface to select an option that is nice and big and easy to choose. Obviously much better than displaying a tiny link.CSS Media Queries and Using Available Space
A tutorial from CSS-Tricks that discusses how to make subtle changes with media queries and how to use media queries in a single style sheet. For instance, if you have a fluid-width design in which the sidebar is 35% of the width of the page, depending on the width of the browser window, you could say, “If the browser is really narrow, do this. If it’s wider, do this. If it’s really wide, do this.” In the article, you’ll learn how to modify a list of links according to the browser’s viewport.Responsive Images, Responsive Videos
Fluid Images
Fluid images are a central aspect of a responsive design. This article by Ethan Marcotte gives a thorough overview on creating them using the classic img { max-width: 100%; } code snippet, as well as details to get you started.Responsive Image: Experimenting With Context-Aware Image Sizing
An alternative approach to fluid images by Filament Group. This technique allows designers to create responsive layouts that serve different image sizes at different resolutions. Effectively, it allows designers to create mobile-optimized images for smaller screens, and then serve higher-resolution versions to larger screens. Filament Group has developed this technique that uses .htaccess files and JavaScript to serve up different sized images based on the screen width. An alternative solution is to use tools like TinySrc which allows you to merely prefix all large images in your source code with a TinySrc URL, and the tool does the rest.Responsive Images and Context-Aware Image Sizing
Craig Russell has developed a technique that uses a server-side script (in PHP) to serve up images of several different resolutions. The idea is that within the PHP script, a nested array is used that lists image files and their relative percentage scales. In HTML, the image’s src attribute would be set to get the requested image’s id, but with no scale specified. A JavaScript calculates the percentage width of the image relative to the maximum width of the container, and this figure is then appended to the end of the src attribute as the scale parameter. The comments in the article contain some nice ideas and suggestions on how the technique could be improved.Responsive Images Right Now
Harry Roberts’ idea is to use the img element for the smaller of the two images, the image that you want mobile users to download. You would also have a containing div to which you apply the large version of the image as a background through CSS. You then hide the img from desktop users, and show them the large CSS background, and hide the background image from mobile users and just serve them the smaller inline image.Responsive Images Using CSS3
Nicolas Gallagher’s method relies on the use of @media queries, CSS3-generated content and the CSS3 extension to the attr() function. By combining the content property with the CSS3 extension to attr(), you are able to specify that an attribute’s value should be interpreted as the URL part of a url() expression. In this case, it means you will be able to replace an image’s content with the image found at the destination URL, stored in a custom HTML data-* attribute.Responsive Images Using Cookies
Keith Clark suggests using cookies to serve smaller images to mobile users. Whenever a browser requests a file from a server, it automatically forwards any cookie data along with the request. If we use JavaScript to populate a cookie with the current screen’s dimensions, all subsequent requests made by the browser will pass this data to the server. In other words, the server would know the screen size of the device that is asking for the file.Responsive Images With ExpressionEngine
John Faulds presents a technique for responsive images that is different from the techniques presented above. It involves querying the device’s user agent string to determine whether it is mobile, and then setting a global variable that can then be used in templates to modify the size of the image output. Basically, only one image gets sent to the browser, but that image is different depending on whether you’re viewing the page on a mobile or desktop device.CSS: Elastic Videos
Nick La applies the max-width: 100%; snippet to videos and presents techniques that make HTML5 videos and object- and iFrame-embedded videos responsive. For the latter, the trick is very simple. Just wrap the embedding code in a div container, and specify a 50% to 60% padding-bottom. Then, specify the child elements (iFrame, object embed) and a 100% width and 100% height, with absolute positioning. This will force the embedded elements to expand full width automatically. Initially discovered by Thierry Koblentz.Resizeable Images (At Full Resolution!)
A quick tutorial from CSS-Tricks on resizing images while maintaining resolution.Responsive Email Newsletters
Optimizing Your Email for Mobile Devices With the Media Query
Wide emails often require horizontal scrolling, especially when there’s a large image. This case study by Campaign Monitor explains how emails can be optimized for mobile devices using media queries and offers a couple of useful techniques and snippets to be used right away.Responsive Design for Email, the Largest Mobile Audience
Another interesting case study that shows how the development team behind Beanstalk applied screen-size-specific media queries to target styles, and what design decisions were made to make the mobile email experience better.Media Queries in HTML Emails
This article covers using media queries to target specific mobile email clients.Guide to CSS Support in Email
Designing an HTML email that renders consistently across major email clients can be time-consuming. Support for even simple CSS varies considerably between clients, and even different versions of the same client. Campaign Monitor has put together a guide to save you the time and frustration of figuring it out for yourself. With 24 different email clients tested, it covers all of the popular applications across desktop, Web and mobile email.Responsive Design Tools
You can build a responsive design from scratch, or you can use some of the tools listed below to speed up and smooth out the process.
Respond.js
Scott Jehl’s fast and lightweight polyfill for min-width and max-width CSS3 media queries (for IE 6 to 8 and more). css3-mediaqueries-js is another script that enables IE 5+, Safari 2 and Firefox 1+ to transparently parse, test and apply CSS3 media queries.WebPutty: Scientific Progress CSS Editing
This tool is a Web-based CSS editor with auto-save feature and a real-time preview of your website. WebPutty also has CSS selector highlighting and SCSS support (for Sass and LESS), as well as Compass support. To use the tool, just embed a link tag at the end of your website’s head tag.Debugging CSS Media Queries
In responsive Web design, we’re working with different states, widths and viewport sizes. Johan Brook shares a quick tip for indicating (with pure CSS) which media query has kicked in. The article also provides a mixin for developers using Sass. A demo is available as well.Responsive Design Testing
This tool is for everyone who needs a quick and easy way to test their website design in multiple screen widths. Change the defaultURL variable at the top of the responsive.js file to your own site and navigate your website from within the frames.Responsive Containers: Selector Queries
This JavaScript by Andy Hume allows you to add selector queries and responsive containers to your design. Essentially, you can apply different class values to an HTML element based on its width.Resize My Browser
If you need your browser to display content in a certain window size this is what you have been looking for. Just click on the size you need and check out what your size looks like. Does not work in Chrome and Opera due to issues with the “ResizeTo” event.Media Query Bookmarklet
A handy tool that shows you exactly what size the viewport has and which media query just fired. Drag it to your bookmarks bar and have it ready when needed.Responsivepx
Use the information this little gadget provides in your media queries to create responsive designs.ProtoFluid
A tool for rapid prototyping of responsive design. You can prototype CSS on a variety of popular device sizes, orientations and browsers, be they phones (BlackBerry Torch, Google Nexus One, iPhone, Motorola Droid), tablets (BlackBerry Playbook, iPad, Samsung Galaxy Tab, Dell Streak), monitors or televisions (720p, 1080p). You can preview designs right in the browser and use your development tools like Firebug. You might want to check an alternative tool ScreenFly as well.Fluid Grid Calculator
Harry Roberts has developed a calculator and generator of fluid grids for your responsive designs. Just provide the number of columns, the width of one column and the width of the gutters, and the tool will generate a fluid grid system in CSS for you. Handy!Free HTML5/CSS3 WordPress 3.1+ Theme With Responsive Layout: Yoko
Yoko is a modern and flexible WordPress theme. With the responsive layout based on CSS3 media queries, the theme adjusts to different screen sizes. The design is optimized for big desktop screens, tablets and small smartphone screens. To make your blog more individual, you can use the new post formats (like gallery, aside or quote), choose your own logo and header image, customize the background and link color.Scherzo, a Responsive WordPress Theme
This WordPress theme is a fine example of responsive design, displaying nicely on almost all devices and screens.Responsive Design Templates
320 and Up
320 and Up works on the “tiny screen first” principle, whereby designs are created for mobile screens first, and then expanded for tablets, desktops, and large screens. It works well as an extension to HTML5 Boilerplate and as a standalone kit.Media Queries for Standard Devices
Here is a useful template for media queries for standard devices: empty placeholders for targeting devices and attributes that you might be interested in when making responsive designs.Mobile Boilerplate
Here is a customizable template for creating rich, high-performance mobile Web apps. You’ll get cross-browser consistency among A-grade smartphones, and fallback support for legacy BlackBerry, Symbian and IE Mobile. You’ll also get offline caching for free, fast button clicks, a media query polyfill and many common mobile Webkit optimizations.Skeleton: Beautiful Boilerplate for Responsive, Mobile-Friendly Development
Skeleton is a small collection of CSS and JavaScript files that can help you rapidly develop websites that look beautiful at any size, be it a 17-inch laptop or an iPhone. Skeleton is a grid that is responsive right down to mobile. It is well organized and well structured and provides most basic styles as a foundation.Responsive Design Frameworks
1140 CSS Grid
1140 CSS Grid is optimized to work on screens ranging from the size of mobiles to 1280 pixels wide. It’s a simple flexible grid system that uses media queries for smaller screens, essentially stacking columns on top of one another.inuit.css
This CSS framework is built to provide a solid foundation for designs on smaller screens (such as tablets) and tiny screens (such as phones) straight out of the box with minimal effort. It also has a custom grid system builder for creating fluid grid systems.Flurid
Flurid is a liquid grid layout with up to 16 columns.FluidGrids
FluidGrids is a fluid grid framework that creates layouts based on 6, 7, 8, 9, 10, 12 or 16 columns.Less Framework 4
A CSS grid system for creating adaptive layouts. It includes four basic layouts (including tablet, mobile and wide mobile), with three sets of typography presets.Fluid Grid System
This fluid grid framework includes a typographic grid and baseline grid.Tiny Fluid Grid
Tiny Fluid Grid helps you generate your own fluid grid with 12, 16 or 24 columns, minimum and maximum widths, and percentage-based gutters.Responsive Design Workflow and Strategies
The Responsive Designer’s Workflow
Luke Wroblewski’s conference notes on Ethan Marcotte’s presentation about applying responsive Web design principles and workflows to the redesign of a major newspaper website. Among other things, Ethan explains how he approaches the responsive design methodology, what the design process looks like and how prototyping is done in the context of responsive design.The Goldilocks Approach to Responsive Web Design
The Goldilocks Approach stresses device-independent layouts that look perfect regardless of the device they’re viewed on.Content Choreography
Read up on how to properly plan your site to live up to todays standards. Begin to choreograph content proportional to size to serve the best possible experience at any width.Structured Content First
In this presentation, Stephen Hay discusses a couple of troubles you might run into when structuring your content and argues that properly structured content is portable to future platforms. Stephen suggests that we think about creating and designing structured content first that caters to the lowest common layout denominator, whether this be a small screen or a text browser. This content should be able to go anywhere.Design for a Target Experience First
Another interesting perspective on a responsive designer’s workflow; Nathan C. Ford focuses on experience of its users first and then derives user scenarios and media queries from it. “There are goals for sites that reach beyond simple readability, where a lack of features can actually diminish the experience. I am working on such a project now. Our approach has been to peruse the research and tailor an optimal experience for the most likely user scenarios. Working out from there, we judicially edit and hone for each media query.”More Responsive Design, Please
This article by Jason Things covers responsive design based on a layout/content/capability/user intent scheme, which sheds interesting new light on the challenges that responsive design can create. It’s a well thought out piece and is certainly worth a read.Breaking Development
Luke Wroblewski took notes at the Breaking Development Conference while Stephen Hay talked about the realities of designing for different device experiences.Patterns for Multiscreen Strategies
Have a look at this simple but effective slideshow to get an idea of which core factors play a role in multiscreen concepts.Responsive Web Design from the Future
According to Kyle Neath, responsive web design is about a lot more than the size of your screen. This talk is about about how GitHub handles links, the url bar, partial page updates, and explains why Kyle thinks the HTML5 history API is the most important thing to happen to front end development since Firebug. An inspiring presentation.Developing a Progressive Mobile Strategy
In this presentation, Dave Olsen presents a progressive mobile strategy that consists of audience strategy, content strategy and platform strategy. Dave argues that to develop a sustainable and scalable mobile strategy, you need to answer the questions, “What value will the targeted audiences get from this content?” and “How do we develop solutions to handle both mobile and native now, as well as the devices of the future?” An interesting presentation.How to Use CSS3 Media Queries to Create a Mobile Version of Your Website
In this Smashing Magazine article, Rachel Andrew explains how, with a few CSS rules, you can create an iPhone version of your website using CSS3 — one that will work now. You’ll see a very simple example and learn the process of adding a small device style sheet to a website to show how easily we can add mobile-specific style sheets to existing websites. You may want to consider reading Aaron Gustafson’s article “Adaptive Layouts With Media Queries” and Emily Lewis’ piece “Respond to Different Devices With CSS3 Media Queries” as well.Discussions and Points of View on Responsive Design
While not tutorials per se, the articles here give you valuable insight into why you should use responsive design techniques (and when you maybe shouldn’t use them).
Responsive by Default
Andy Hume explains what in his opinion responsiveness is all about. It’s what a website does when it’s loaded into an unknown browser on an unknown device by an unknown individual. It’s “how you deal with “the most hostile software development environment ever imagined” (via Douglas Crockford). Like progressive enhancement it’s a strategy that frees you to work with the web rather than fight against it.” An interesting point of view.Responsive Web Design or Separate Mobile Site? Eh, It Depends
An interesting article discussing the pros and cons of responsive designs vs. dedicated mobile websites.The Case Against Responsive Web Design
It seems only fair to include some dissenting opinions here about when responsive design is and is not appropriate. This article discusses why responsive design doesn’t always make sense from a user experience perspective. Take a look in the comments section, too. Luke Jones has a similar opinion.A Responsive Mind
A discussion on Jeremy Keith’s blog about the necessary parts of a responsive design and how to effectively create different layouts based on different screen sizes. Examples are included.Responsive Enhancement
An excellent introduction to responsive design as a way of thinking rather than as a tool or technique. Jeremy Keith argues that responsive Web design can’t be tacked on to the end of an existing workflow. Instead of pixel perfection, we should be thinking of proportion perfection. An inspiring read.Mobile-First Responsive Web Design
Mobile First Responsive Web Design is a combination of philosophies and strategies with the aim to achieve a wider application of best practices in the area.Where are the Mobile First Web Designs?
In this article Jason Grigsby presents the findings from his study on responsive designs, their features and appearance as well as general remarks on the state of art of Responsive Web Design.Further Resources
Here are some additional resources for creating responsive designs that don’t fit neatly into the categories above.
Media Queries
A growing collection of websites that use media queries.Responsive Web Design, by Ethan Marcotte
This book, written by Ethan Marcotte and published by A Book Apart, is a fantastic resource for learning how to design responsive websites. It covers the basics of the responsive Web, flexible grid systems, flexible images and media queries, and it gives insight into how to create responsive designs.The Big Web Show Episode #9: Responsive Web Design
Jeffrey Zeldman and Dan Benjamin sit down with Ethan Marcotte for episode 9 of The Big Web Show to discuss responsive design, among other topics.Last Click
The Latest in HTML5
This slideshow covers some techniques and lesser-known HTML5 gems that could get implemented in browsers in the near future: among other things, server-side media queries with JavaScript and form-factor detection.Would you like to see more round-ups like this one on SM?
Would you like to see more round-ups like this one on Smashing Magazine?
(al)
Building a Frameless grid
1. Make a regular fixed-width grid.
Pick a column width, a gutter width… you know, the usual stuff. Don’t worry about the amount of columns just yet, but otherwise use whatever criteria it is that you usually use to create fixed-width grids. I recommend using a relatively small column width for added flexibility.
2. Make it repeat infinitely.
Now, give your grid an infinite number of columns, so that no matter how wide you make your viewport, more and more columns come into view. Imagine you’re looking at an infinitely wide honeycomb filled with columns instead of hexagons.
3. Center it in the viewport.
Align your grid horizontally to the middle of your viewport. For a grid with an even number of columns (pictured), align the center point of your viewport in the middle of the gutter between your two centermost columns. For an odd-numbered grid, align it in the middle of your centermost column.
4. That’s it, really.
Start using the grid. Use media queries to adapt your design as more columns become available. Since you’ll be adapting column by column instead of pixel by pixel, you can choose exactly when your layout should and shouldn’t adapt. This site, for example, only adapts around 320, 480, 600, 900 and 1900 pixels. To see it in action, try resizing your browser window.
Downloads, on GitHub
Contains a small CSS reset, some consistency fixes, as well as some super-basic customizable variables and functions for starting off a Frameless grid. A good starting point for LESS users.
The same as the LESS version above, but written in SCSS instead. Makes for a nice starting point for SASS users.
This is what I use as a blank canvas. Contains some basic HTML5, including Paul Irish’s conditional classes, the HTML5 Shim, and a proper meta viewport tag.
A basic template for a Frameless grid with 48 px columns and 24 px gutters — same as the grid used on this site. Includes columns marked up with guides up to 2560px, and overlay masks for some common screen sizes.
JS Grid overlay script
(Coming soon.) Lets you overlay a customized Frameless grid on top of your site. Handy for designing in the browser.
Tips & FAQs
Is Frameless a framework?
Nope. It doesn’t include any code. It’s just an idea for a specific type of adaptive grid. You can use it as a good starting point for a new design, but you’ll still have to do all the hard work of designing and coding yourself.
Is Frameless responsive?
"Responsive web design“, as defined by its coiner, Ethan Marcotte, consists of three components: a fluid grid, fluid media, and media queries. The Frameless grid is fixed-width, not fluid.
Frameless is the spiritual successor to Less Framework. It’s a much simpler idea, more flexible, and hopefully easier to integrate into your design workflow.
Don’t adapt unless it makes sense.
Only adapt your design when it makes sense for the content to adapt. You don’t have to fill up every column at every possible screen size.
Start from the smallest possible size and work your way upwards. Adaptive designs tend to just work out better this way.
Leave IE6–8 behind.
Old IE won’t see any styles that are inside a media query, so just serve it your mobile layout and enhance it a little using IE-specific classes. It’ll make your life much easier. More about this in my blog post: Leaving Old Internet Explorer Behind.
Mobile Safari causing trouble?
Does your site zoom in too much when changing orientations on an iOS device? It’s because of this Mobile Safari bug.
(Hello! If you think this article’s interesting, you might check out my ALA article on responsive web design.)
I’ve always hated publishing. I don’t mean the industry, but the act. Hitting “print,” sending an email, pressing that “Publish” button on the CMS: at some point, you relinquish your ability to smooth down some of the sharper edges, fill in the holes of your argument, and just generally fix whatever’s broken. At some point, you just accept what’s on the page, tousle its hair a bit, and send it off into the world at large to be judged, poked, and prodded. But that doesn’t mean you stop thinking about the article, what you could’ve done differently, and what you wished you’d included.
To wit:
One of the really solid criticisms lobbied against my Fluid Grids article for ALA was that all of my examples were pretty text-heavy. As a result, they all more or less ignored the issue I raised at the end of the essay: that working with non-fixed layouts can be more difficult once you introduce fixed-width elements into them. By default, an image element that’s sized at, say, 500px doesn’t exactly play nicely with an container that can be as large as 800px, but as small as 100px. What’s a designer to do?
In Which “Looking Across the Pond for Help” Is a Pretty Decent Answer, As It Turns Out
Since I started mucking around with this whole “stylesheets” thing, Richard Rutter has been one of those CSS giants on whose shoulders I frequently stand. His 62.5% technique was one I used for ages, and his work on sizing em-based text really provided the inspiration for cracking the whole “fluid grid” problem.
A few years back, Richard published a brilliant series of experiments with max-width and images, which I pored over when I was first working on this blog. Ultimately, I decided to use the approach from his third example, which was to set a max-width of 100% on all images on my website:
- img {
- max-width: 100%;
- }
This solved the problem beautifully. Instead of just rendering at its native width and overflowing its containing box, the image would render at its native dimensions as long as its width didn’t exceed the width of its container. Here’s a quick test case I tossed together, using the text from one of my old blog entries as the image. Try resizing your browser window—looks great, right? Modern browsers are intelligent enough to keep the image’s proportions intact, even as the page scales up or down accordingly.
And as it turns out, this works just fine for most embedded videos, too:
- img,
- object {
- max-width: 100%;
- }
So while this is shaping up nicely, we’re not quite done. As you may well know, older versions of Internet Explorer would rather smear poo in their hair than render a proper stylesheet don’t support max-width. So for especially large images, I’ve been relying on a simple width: 100% rule in an IE-specific stylesheet, like so:
- img {
- width: 100%;
- }
With that, the larger issue was basically sorted: namely, that a non-fixed page’s layout won’t break if images or stupid Youtube movies were dropped into the markup. Hooray, right?
As it turns out, not quite. Not quite hooray at all.
In Which a Particular Platform Causes Issues, and While I Don’t Want to Call Anybody Out or Anything, Its Name Rhymes With “Blindows”
If you’ve been looking at the little test case on Windows, there’s a good chance that the image quality, well, looks awful as it scales down. The challenging bit is that this isn’t a browser-specific problem, but a platform-specific one: native image scaling on Windows just, well, kind of sucks. Specifically, if you’re on any version of Internet Explorer (prior to version IE8) or on a version of Firefox older than 3.0 on Windows, things look decidedly janky: the text gets painfully artifacted as the image resizes, beyond the point of maintaining any semblance of legibility. Thankfully, it’s fixable.
But first, the bad news: as far as I can tell, we have to write off Firefox 2 and below. While we could target those browsers on Windows with JavaScript, it’d be unfortunately reliant on user agent sniffing—and even if we wanted to go down that path, there’s no way to ask Firefox on Windows to toggle its “not horrendous” image rendering engine.
In Which I’m Actually Grateful for an IE-Specific, Non-Valid CSS Filter (I Know, I’m As Surprised As You Are)
Internet Explorer, however, does have such a toggle. When I was working on the (apparently discarded) W3C.org redesign last year, I discovered that Microsoft’s AlphaImageLoader property–the one we so frequently use to fix IE’s PNG transparency–kicks IE’s rendering engine into high gear…or at least into some acceptable level of not-suckage. (More recently, the Flickr team blogged about this very thing.) And as soon as I applied a PNG fix script to not just, well, PNGs but all images in the document, the image quality in IE improved sharply. The text looked crisp and legible, even at smaller window widths.
Sadly, it also caused another bug. Since the higher-quality AlphaImageLoader sort-of-object-thing sits between the image and its background, the scripts replace the src attribute of the img element with a transparent “spacer” GIF, and resizes to match the size of the original element. This hoop-jumping lets the AlphaImageLoader shine through. Unfortunately, this pretty much thwarts our max-width: 100%/width: 100% approach: since the GIF has its own physical dimensions (usually 1×1), it won’t really “scale” proportionally as its container changes shape. Instead, the spacer’s width will change dynamically, but its height is fixed at the initial value set by the PNG script.
So that’s why I whipped up this little script. In short, it cycles through your document, swaps out the images for a transparent GIF, and applies the AlphaImageLoader property to each one. Then, whenever the window’s resized, the script automatically recalculates the proper, proportional height and width of the image, and resizes the spacer graphic accordingly.
Here’s the script in full:
- var imgSizer = {
- Config : {
- imgCache : []
- ,spacer : "/path/to/your/spacer.gif"
- }
- ,collate : function(aScope) {
- var isOldIE = (document.all && !window.opera && !window.XDomainRequest) ? 1 : 0;
- if (isOldIE && document.getElementsByTagName) {
- var c = imgSizer;
- var imgCache = c.Config.imgCache;
- var images = (aScope && aScope.length) ? aScope : document.getElementsByTagName("img");
- for (var i = 0; i < images.length; i++) {
- images.origWidth = images.offsetWidth;
- images.origHeight = images.offsetHeight;
- imgCache.push(images);
- c.ieAlpha(images);
- images.style.width = "100%";
- }
- if (imgCache.length) {
- c.resize(function() {
- for (var i = 0; i < imgCache.length; i++) {
- var ratio = (imgCache.offsetWidth / imgCache.origWidth);
- imgCache.style.height = (imgCache.origHeight * ratio) + "px";
- }
- });
- }
- }
- }
- ,ieAlpha : function(img) {
- var c = imgSizer;
- if (img.oldSrc) {
- img.src = img.oldSrc;
- }
- var src = img.src;
- img.style.width = img.offsetWidth + "px";
- img.style.height = img.offsetHeight + "px";
- img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')"
- img.oldSrc = src;
- img.src = c.Config.spacer;
- }
- // Ghettomodified version of Simon Willison's addLoadEvent() -- http://simonwillison.net/2004/May/26/addLoadEvent/
- ,resize : function(func) {
- var oldonresize = window.onresize;
- if (typeof window.onresize != 'function') {
- window.onresize = func;
- } else {
- window.onresize = function() {
- if (oldonresize) {
- oldonresize();
- }
- func();
- }
- }
- }
- }
You can see it in action (screenshot of the working page in IE7), and download the script if you like. Simply update the path to your spacer graphic at the top of the code, invoke imgSizer.collate(); at window.onload (I prefer Simon Willison’s excellent addLoadEvent(), myself), and the script’ll apply the fix to all img elements on a page. Alternately, if you want to limit the scope, you can pass in a collection of img elements as an argument, thusly:
- addLoadEvent(function() {
- if (document.getElementById && document.getElementsByTagName) {
- var aImgs = document.getElementById("content").getElementsByTagName("img");
- imgSizer.collate(aImgs);
- }
- });
Drop max-width: 100% into your CSS, and rock the imgSizer script, and your fluid images should look impossibly fine.
In Which I Write a Pithy Conclusion Title
I wanted to write this up largely because, well, I think it could use a second pair of eyes. The technique works, but I could use any suggestions/criticisms you might have. It’s working well enough on my blog, and performed admirably on Airbag’s W3C.org redesign, but I’m sure there’s room for improvement. If you have any recommendations for how I could make this script Suck Less™, I’d love to hear it in the comments, or via email.
Thanks for reading.