Mobilizing Drupal

320 x 480 Safari screenshot

Here is a gallery site in Drupal that displays a Views grid of photos on the front page. It actually displayed fairly well on the iPhone since it is 960 pixels wide (which is what the iPhone assumes by default), but I wanted to serve a special style sheet to iPhones. Here's how I did it.

From my theme folder (sites/all/themes/starbar) I opened page.tpl.php and style.css. I made 2 copies of style.css - one called screen.css and one called mobile.css. I then erased most of style.css leaving just the css reset portion of it. Then I erased the reset portion of screen.css - so style.css and screen.css combined do what style.css used to do by itself.

I modified mobile.css to style the display for the iPhone. Mostly I just re-sized the images and a couple font sizes.

Then to page.tpl.php I added a few key lines. In the head of the document I added the meta tag <meta name="viewport" content="width=device-width" />, which causes the iPhone to display the page at the device width (e.g. 320) instead of assuming its 960 pixels wide as mentioned earlier.

After the line "<?php print $styles ?>" which load Drupal's various stylesheets (including, by default in Drupal 6, the theme's sytle.css file), I added this snippet of PHP code.

$mybrowser = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
if ($mybrowser == true) {
print '<link type="text/css" rel="stylesheet" media="all" href="/bars/sites/all/themes/starbar/mobile.css" />';
} else {
print '<link type="text/css" rel="stylesheet" media="all" href="/bars/sites/all/themes/starbar/screen.css" >

This code checks for the position of "iPhone" in the HTTP_USER_AGENT. If it finds it, it loads the mobile.css stylesheet. If not, it loads the desktop.css style sheet.

That's all there is to it!