Determine iPhone orientation using CSS
With the beta of Firefox 3.5 showcasing 35 new features over 35 days, the article on CSS3 media queries stuck out, the orientation detection really got my attention and immediately put my thought process to mobile devices, in my case the iPhone. I thought this is great maybe this has been snuck into the iPhone 3.0, unfortunately for us it wasn’t. That didn’t stop me and I got thinking about how it could be done if at all on the iPhone without using JavaScript.
Still using the CSS3 media queries we can accomplish orientation detection with only CSS but instead of looking at the unsupported orientation property we can use the min-width and max-width propertities to our advantage to detect what orientation the user is currently in. Load the below demo in your iPhone/iPod Touch to see it in action, rotating the phone will either change the text from “Portrait” to “Landscape” depending on your orientation respectively.
Looking in the Apple Developer documentation on Human Interface Guidelines (HIG) we can determine the min and max width we need to target to find out the user orientation. Let’s look at the CSS from the demo to better understand how it works.
In the demo we have a set with to display: table-cell, this isn’t important to the demo but allows me to easily vertically centre the text. Inside the there are 2 spans which will show or hide depending on what orientation you’re in, initially we hide both spans.
The next few lines are where we can figure out using only CSS what span to show. To determine if the user is in portrait mode we use the media query @media screen and (max-width: 320px) we know from the HIG that 320px is the max-width in portrait mode. We do the same for landscape but this time we use min-width and increase the value by 1 so viewport needs to be at least 321px wide before any styles in the media query will be applied. Inside each media query I use the CSS3 nth-child pseudo class to target an individual span.
Not without issues
In order for this to work we need to add the viewport meta tag to force the iPhone Safari viewport width to be that of the device, it is usually defaulted to 980.
My original idea was to use the max-device-width and min-device-width properties which would bypass the need for viewport meta tag but unfortunately this doesn’t work. It may be due to the fact that it will always return a min-width of 320 and a max-width of 480 and therefore wouldn’t be possible to do it the current way I have devised.
Until the iPhone adds in support for the orientation media query, this technique is quite a capable work around. Of course there are still some things it can’t do so the orientation event handler will still be needed for more advanced changes to happen.