Create mobile site layouts with CSS Media Queries

Web sites and apps need to deal with the challenge of serving content to a multitude of browsers and devices. People access web sites and apps via tablets and mobile phones more than ever before, and smart phone usage numbers are growing exponentially. In some populations, mobile Web traffic is higher than traffic from desktops. Technology nowadays means devices and machines range in size from quite small to quite big, and as a result, you the developer must format the content appropriately for each device type. You can accomplish this task by using CSS Media Queries, as they are the best foundation of a responsive UI.

What is a CSS Media Query?

In the past, in order to serve browser or device specific content, we would write code that determines which style sheet to use based on feature detection (or UA detection on older Web sites). Now, instead of having to write code, we can use declarative CSS Media Queries to apply rules to an HTML page based on the requesting device’s characteristics. CSS Media Queries are a way to apply different styles when the requesting browser or device matches the conditions within the media query. With media queries you can target various screen sizes, orientations, and form factors including TV and print, and serve tailored content to them. For example, the media queries below apply a different layout to the tablet sized, landscape screen (768 x 1366 ), vs. the phone sized, portrait screen (320 x 480):

@media screen and (min-width: 768px) and (orientation: landscape)

{
    /* CSS layout for screens with minimum 800px width, landscape */

} @media screen and (max-width: 320px) and (orientation: portrait)

{
    /* CSS layout for screens with maximum 320px width, portrait */
}

While multiple media queries can exist side by side in a single .css file (like the example above), maintenance can be easier if you create one .css file for each type of device you want to support. Doing so allows you to swap style sheets based on the media query defined in the media attribute of the <link> tag.

<link rel=”stylesheet” type=”text/css” href=”smartphones.css” media=”only screen and (max-device-width: 320px)” /> <link rel=”stylesheet” type=”text/css” href=”tablets.css” media

="screen and (min-device-width: 800px)" />

Effectively, media queries rid you of the long lines of “if then” statements otherwise required as conditional logic to figure which style sheet to use for which occasion. You no longer need to resort to using JavaScript to swap style sheets by querying user agents, media types or common device form factors.

Design a page layout with CSS Media Queries

Layouts that fit traditional landscape screens work horribly on smart phones, and thus the need for a responsive layout. A responsive layout is fluid and adaptable, and needs flexible elements such as grids and images that can automatically resize based on the form factor of the requesting device. In addition to resizing elements, you must adapt the page to remove content or unnecessary navigation, because space is at such a premium on small devices.

CSS Media Queries are the foundation of responsive layouts that work across devices. Let’s start with an example of a simple web page with a two column layout in which there is a container <div> and two child <div> tags that render the columns. This layout is for desktop browsers, and later we’ll modify it to run on a phone.

#wrapper 

{ margin:0 auto; height:768px; } #sidebar { background-color:#2885c9; width:24%; height:600px; float:left; } #content { background-color:#229731; width:75%; height:600px; float:right

;
}

<!DOCTYPE html> <html xmlns=”http://www.w3.org/1999/xhtml”> <head> <title>CSS Media Queries</title> <link href=”default.css” rel=”stylesheet” /> </head> <body> <div id=”wrapper”> <div id=”sidebar”><span>Side bar</span></div> <div id=”content”><span>Content goes here.</span></div> </div> </body> </html>

The code above looks like this in IE 10, a desktop browser. There is a column to the left (side bar) and one on the right (content).

 

image_thumb3_2

Of course, this layout just won’t work in a small, portrait, screen. Most side bars are for navigation, that when mobilized is painful to use in such a small form. Repositioning the elements so that the side bar is on top of the content is a much better layout for smart phones, because of the change in orientation. We can do this by creating a media query and modifying the CSS to fit smart phone dimensions. Below is a media query definition containing the same three selectors in the previous sample, but modified for a smart phone layout. What was the leftmost column (the side bar) is now positioned at row #1, and its adjacent content area is now positioned at row #2. As you might expect, the sizes of the elements are smaller than in the desktop version.

@media screen and (max-width: 320px) and (orientation: portrait) { #wrapper { width:320px; height:480px; margin: 0 0 0 5px; } #sidebar { width:320px; height:90px; float:left; margin: 0 0 5px 0; } #content { width:320px; height:380px; float:left

;
    }
}

 

image_thumb2_2SNAGHTML103a6a17_thumb1_2

The media query works great in IE10 desktop when resized to smart phone dimensions (left side, above image). However, in some phones or emulators, the above media query does not work (right side, above image). This is because we are missing a key component in mobilizing content – the <viewport> meta.

Mobilizing sites with the viewport meta

When mobile devices receive content formatted for the desktop or larger sized browsers, their default action is to zoom out to show all the content. The phone browser tries to show the page as a desktop browser does but condensed into its tiny, portrait, view. They do this for backward compatibility of the many non-mobilized sites that phones otherwise render incorrectly and break. We can change this behavior and tell phones to optimize their default zoom for mobile by using the viewport meta element. The viewport meta instructs mobile devices to resize the content to fit on their screen or to a certain scale based on the tag’s attribute values. Below is an all-purpose viewport that resizes content to fit the device:

<meta name=“viewport” content=“width=device-width”/>

If you aren’t sure what attributes to use, use the above as the default, as it renders the page to fit the device. Now because the phone will render the content correctly, and the output looks like the following:

SNAGHTML9843bc_thumb1_thumb

Notice the browser has applied the media query this time. This is because the phone’s browser took a cue from the viewport and rendered the page like a mobile browser rather than a desktop browser.

Summary

As you can see, CSS Media Queries are the best way to deliver perfectly fitted content to any device, with less maintenance hassles. Media queries aren’t just for the Web either – you can write Windows Store apps in HTML/CSS/JavaScript and use media queries for Windows 8 features like Snap-View. If you are working cross platform, don’t worry about support as CSS Media Queries have a wide adoption across desktop and mobile browsers.

Lastly, if you would like to go mobile but must support the older-than-dirt browsers like IE8 and below then check out Respond.js. Respond is a polyfill for CSS Media Queries (a mechanism for backwards compatibility), enabling their use in old or unpopular browsers.