2010-11-30

Specifying different CSS for landscape and portrait orientations on the iPad

I have a web app that uses jQuery UI buttons. I noticed that on my iPad the buttons worked fine in portrait orientation, but in landscape orientation the buttons, and even regular links in a table, would not work properly when pressed (a different button or link than the one pressed would fire). I determined that this problem was caused by the following tag in my HTML:

<meta name='viewport' content='width=device-width' />

Using this tag causes Safari Mobile (the iPad browser) to zoom in on the page a bit in landscape orientation, making the fonts a bit bigger, which would be fine except that it apparently breaks link and button functionality in some cases. I got the buttons and links to work properly by using this tag instead:

<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' />

This locks down the page so it doesn't (and can't) zoom in or out.

That fixed my broken buttons and links in landscape orientation, but I had really liked the way the fonts got bigger in landscape orientation. It gave me a way to have two different zoom levels in may app. If I wanted to see more content in a small font I used portrait; if I wanted to see less content in a bigger font I used landscape.

So, I figured out how to get the exact same effect using CSS "media queries." Here is some CSS that first sets styles for the iPad regardless of orientation and then specifies different styles for portrait and landscape orientation:

@media only screen and (max-device-width: 1024px)
{/* This block specifies CSS that only applies to an iPad
max-device-width: 1024px seems to only select the iPad*/

body
{margin-left: 0px;
margin-top: 0px;}

}

@media only screen and (max-device-width: 1024px) and (orientation: portrait)
{/* This block provides CSS that only applies to the iPad in portrait orientation */

body
{font-size: 16px;}

}

@media only screen and (max-device-width: 1024px) and (orientation: landscape)
{/* This CSS kicks in only when an iPad is in landscape mode. It makes the font bigger, the table rows taller, etc */

body
{font-size: 18px;}

}


You can put this block of CSS at the end of the regular stylesheet for a page and it will apply different CSS when the page is viewed on the iPad, allowing you to have a completely different layout on the iPad than you have on a regular browser. What is remarkable to me is how smoothly the styles change when I switch orientation on the iPad; I was afraid there would be lag while the page reformatted but I can't detect any.

2 comments:

Anonymous said...

Thanks - that is a neat and elegant solution!

Anonymous said...

That is pretty darn cool. I appreciate the share here. Iv'e been looking for something like this everywhere. You are a smart, smart man. Or women. :P