Create a mobile phone version of your website with CSS3 Media Queries

HTML 4 and CSS2 came with support for media-dependent style sheets.

For example a web page for display on screen could have a black background, but have a white (or no) background when printed out.

In CSS3 media queries extend the functionality with features such as 'width', 'height' and 'color'. A design can be tailored to a specific range of output devices without changing the content itself.

Following the recent rise of the mobile WebKit, media queries became a popular way of delivering a tailored style sheet to the Apple iPhone, Google Android phones and others. And with the emergence of small tablet devices such as the iPad and Playbook there is more need to ensure that content is automatically adjusted to fit all display resolution and devices.

Here's how media types were used in CSS 2.1:

A different style sheet could be specified depending on whether the device was a screen or a printer.

Now CSS 3 has improved up media types with media queries. A media query allows us to inspect the physical characteristics of a device:

The media query contains the media type, in this case "screen", the "and" keyword, the media feature to inspect "(max-device-width)" and finally the value "480px". So if the viewport is smaller than 480px (the width of the iPhone screen in landscape orientation) then the mobile.css style sheet is loaded.

Media queries can also be used with the CSS file either as part of the @media rule:

@media screen and (max-device-width: 480px) { 
  /* css rules here */ 
}

Or as part of an @import directive:

@import url("mobile.css") screen and (max-device-width: 480px);

So if the device passes the conditional statement of our media query, the CSS will be loaded. So rather than targetng a specific version of a specific browser or even using Javascript solutions, we can look to correct issues with layout as it scales beyond its initial or ideal resolution.

There are some great examples of using CSS3 Media Queries along with images and examples by Nick La on Web Designer Wall and Rachel Andrew on Smashing Magazine.

Top livechat