Three Ways to Handle Orientation Change on Your Mobile Web Site

Most of the projects that I have worked on used a desktop web browser for a front end.  The nice thing about desktop computers is that people don’t go around flipping monitors onto their sides.  Another nice thing is that users either keep their browser windows full screen or they are smart enough to know how to re-size it to fit your web site nicely.  Developing for mobile platforms is a bit more complicated.

The first problem is that a user can rotate their device.  The second is that users can’t exactly re-size your browser window in the traditional sense.  Sure, they can zoom in and out, but that doesn’t change the aspect ratio of your site.  To make things worse, a mobile site needs to be viewable on a wide range of device sizes.  Everything from a 240x320 Blackberry to a 1024x768 iPad is fair game for your test team.

After a bit of research and experimentation I’ve found three ways that you can handle rotation and content layout.  Surely there are more systems to deal with the problem, but these have covered all my needs so far.

#1 Fluid Layout

This is probably the simplest and most familiar to traditional web developers.  It does require some advanced planning though.  When you are starting on your design, arrange your content into blocks and set them all floating left.  As your screen size and shape changes, the mobile browser will display your content as best it can.  If you planned well and your content is amenable to this technique, this can look good.

#2 Provide Alternate CSS for Portrate and Landscape

Similar to #1, this requires some planning.  Keep your design modular and use CSS to lay everything out, but design two (or more) sets of css layouts.  You can wrap your css layout in @meda selectors like this:

One layout for portrait and one for landscape.  You then wrap each CSS layout in media selectors like this:

@media screen and (orientation:portrait) { … }
@media screen and (orientation:landscape) { … }

If your design needs to be tweaked for different resolutions, you can even do that with a media tag like:

@media (min-width:500px) and (max-width:900px) { … }

#3 onorientationchange JavaScript

Finally, if you want to modify your layout, or do anything else, using JavaScript when the orientation changes you can bind to the onorientationchange hook:

window.onorientationchange = function() {
switch (window.orientation) {
case 0:
// run your JavaScript for portrait mode here
break;
case 90:
// run your JavaScript for landscape mode with the screen turned left
break;
case -90:
// run your JavaScript for landscape mode with the screen turned left
break;
}
}