Saturday, September 22, 2012

Quick Guide to Adding a Mobile Stylesheet to Your Site

Do you want your site to look alright on a mobile device? Do you want to avoid using Foundation, Twitter Bootstrap, or any other front-end web framework? Here’s a four-line guide to having a separate stylesheet for iPod Touch/iPhone 4 (and maybe some other devices).

Put this in your web page’s header:


<link href="/css/main.css" rel="stylesheet" media="screen and (min-device-width: 768px)">
<link href="/css/mobile.css" rel="stylesheet" media="screen and (max-device-width: 767px)">


Where “/css/main.css” and “/css/mobile.css” are your desktop and mobile style files.

What with the 768?

It’s the width in the screen resolution of 1024x768. That’s the resolution of the iPad 2, so users on the iPad 2 will use the desktop stylesheet.

What with the 767?


It’s a quick-and-dirty fix so that devices like the iPad don’t try to load both styles at the same time. Foundation’s CSS file constantly references this number with regard to mobile devices, so I might be onto something.

Will This Work With Retina Displays or Tablets?

You need to tweak the numbers a little for tablets. I don’t have access to a device with a Retina display.

Can This Break My Existing Desktop Layout?

Visitors stuck with a display resolution of 800x600 will be forced into viewing the mobile layout. Twitter Bootstrap (at the time of this writing) does the exact same thing. Foundation only does this for visitors at 640x480! Then again, you’ll have to make significant changes to your site’s markup (and existing styles) to use Bootstrap or Foundation.

Can Resizing the Window Force My Page to Use the Mobile Style?

Nope. The media attributes list ‘min-device-width’ and ‘max-device-width’ instead of ‘min-width’ and ‘max-width,’ so resizing the browser window will not change the style. If you want this behavior, use ‘min-width’ instead of ‘min-device-width’ and ‘max-width’ instead of ‘max-device-width’.

Is This Four-Line Guide Perfect?

I’m not an expert in designing interfaces for mobile devices, so no. Use those four lines of information at your own risk!