After rebuilding a few sites for mobile this weekend I’ve learned a few things about CSS3 media queries and designing for mobile.

1. Include a meta viewport tag

<meta name="viewport" content="width=device-width">

2. Create one design for 768 pixels and up (netbooks, iPads and other screens) and 767 pixels and down (mobile).

@media only screen and (max-width: 767px) {
 // put mobile css here.
}

3. Instead of setting the widths of mobile layouts in pixels, trying using percentages.

There’s a whole explanation of how the viewport works with various mobile resolutions.

The iPhone 4 resolution

The resolution of the iPhone is 960 x 640.

The Google Nexus one resolution

480 x 800

The HTC Desire resolution

800 x 480

The LG Optimus One and older iPhones

320 x 480

As you can see, all of these devices have different reolutions. Doing layouts in pixels will force you to make separate media queries for each device!

As an example – the iPhone 4 and 4s. With the Retina display (326 pixels per inch), displaying a layout in portrait mode means that a design that you created in pixels would require a whole separate layout be created in your stylesheet:

only screen and (-webkit-min-device-pixel-ratio: 2) {
 // iPhone 4 uses double the pixels of older devices
}

Don’t try to do this! You can avoid making a separate layout for each mobile device by setting the viewport meta tag and using percentages in your CSS whenever possible. Yes, you can probably set your #wrapper div to be 320 pixels (which would actually work for an iPhone 4 in portrait mode) but you can also set your form inputs and textareas to be 100%.

<meta name="viewport" content="width=device-width">

The other nice thing about setting up the viewport this way, is, you can build your layout in a browser and then just resize your browser to get an idea of how your layout will look on a mobile device – while still having access to things like Firebug, the web inspector on Safari and Chrome, or the Web Developer’s toolbar.