Working with CSS Media Queries and Media Types, Part 2

Use media queries to adapt a website for mobile device screens of various sizes

Dan Wahlin

August 21, 2012

10 Min Read
Cable car on line en route to green island blue sky background

With more and more Internet traffic now coming from mobile devices, it's time to start thinking about how your website can be optimized to look good and function well on phones, tablets, and other devices, if you haven't thought about it already. Although there's no magic pill to transform a site to look good across multiple devices, you can start the process by integrating Cascading Style Sheets (CSS) media queries into your site. Media queries provide a way to dynamically reorganize content in a page using pure CSS. Although they aren't the only thing to consider when creating mobile-optimized sites, CSS media queries do provide a simple way to repurpose existing content without changing back-end code.

In the previous article of this series, "Working with CSS Media Queries and Media Types, Part 1," I introduced the concept of CSS media queries and discussed the fundamentals of how you can use media queries to target different screen sizes. I showed how you could use media queries to convert a three-column–wide page into a more vertical view of data suitable for devices such as an iPhone, as shown in Figure 1.

Figure 1: Converting a standard website into a mobile-optimized site using CSS media queries

The top part of Figure 1 represents a simple web page displayed in the browser. When the site is viewed on a mobile device, it's transformed dynamically according to the screen width. In this article, I'll provide an additional look at how CSS media queries can be used to mobile-enable a sample website called Widget Masters, shown in Figure 2, without having to change any server-side code or HTML code.

Figure 2: Widget Masters sample website

As shown in Figure 2, this site has some of the standard items that appear in most websites today, including the title area, menu bar, and sections where data is displayed. Without including CSS media queries, the site is readable but has to be zoomed out for a user to see everything, cuts off some of the menu items, and requires horizontal scrolling to get to additional content, as you can see in the example in Figure 3.

Figure 3: Viewing the Widget Masters site on a mobile device

Although the site works on mobile devices, it's definitely not optimized for mobile. Let's see what we can do to optimize the site for mobile viewing by using CSS media queries to override existing styles in the site based on different screen widths.

Adding CSS Media Queries into the Mix

The Widget Masters website relies on standard CSS combined with HTML5 elements to provide the layout shown in Figure 2. For example, to lay out the menu bar shown at the top of the page, the nav element is used, as you can see in the code in Figure 4.

        Home    Products    About Us    Contact Us    Store    

You could certainly use a standard div element instead, if desired. The HTML in Figure 4 is combined with the CSS shown in Figure 5 to add a CSS3 gradient, handle the horizontal orientation, and add some general hover effects.

nav {    width: 100%;}nav ul {    border-radius: 6px;    height: 40px;    width: 100%;    margin: 0;    padding: 0;    background: rgb(125,126,125); /* Old browsers */    background: -moz-linear-gradient(top,  rgba(125,126,125,1) 0%,        rgba(14,14,14,1) 100%); /* FF3.6+ */    background: -webkit-gradient(linear, left top, left bottom,        color-stop(0%,rgba(125,126,125,1)),        color-stop(100%,rgba(14,14,14,1))); /* Chrome,Safari4+ */    background: -webkit-linear-gradient(top,  rgba(125,126,125,1) 0%,        rgba(14,14,14,1) 100%); /* Chrome10+,Safari5.1+ */    background: -o-linear-gradient(top,  rgba(125,126,125,1) 0%,        rgba(14,14,14,1) 100%); /* Opera 11.10+ */    background: -ms-linear-gradient(top,  rgba(125,126,125,1) 0%,        rgba(14,14,14,1) 100%); /* IE10+ */    background: linear-gradient(top,  rgba(125,126,125,1) 0%,        rgba(14,14,14,1) 100%); /* W3C */    filter: progid:DXImageTransform.Microsoft.gradient(        startColorstr='#7d7e7d',        endColorstr='#0e0e0e',GradientType=0 ); /* IE6-9 */}nav ul > li {    list-style: none;    float: left;    margin: 0;    padding: 0;}nav ul > li:first-child {    margin-left: 8px;}nav ul > li > a {    color: #ccc;    text-decoration: none;    line-height: 2.8em;    font-size: 0.95em;    font-weight: bold;    padding: 8px 25px 7px 25px;    font-family: Arial, Helvetica, sans-serif;}nav ul > li a:hover {    background-color: rgba(0, 0, 0, 0.1);    color: #fff;}

When mobile devices hit the site, the layout of the menu items needs to be adjusted so that they're all visible without users having to swipe left or right to access them. This type of modification can be accomplished using CSS media queries by targeting specific screen sizes. To start, you can add a media query into the site's CSS file, as shown next:

@media screen and (max-width:320px) {    /* CSS style overrides for this screen width go here */}

This media query targets screens that have a maximum width of 320 pixels. Additional types of queries can also be added; refer to " Working with CSS Media Queries and Media Types, Part 1" for more details, as well as resources that you can use to test media queries in different devices. In that article, I emphasize (and I'll emphasize again) that CSS media queries only modify the overall layout and look and feel of a site. They don't optimize the site as far as the size of the images or content sent to the device, which is important to keep in mind.

To make the navigation menu more accessible on devices such as an iPhone or Android, you can use the CSS shown in Figure 6.

@media screen and (max-width:320px) {    nav ul   {    height: 100%;    }    nav ul > li {    float: none;    }    nav ul > li a {    line-height: 1.5em;    }    nav ul > li:first-child {    margin-left: 0px;    }/* Additional CSS overrides go here */}

This code changes the height of the menu from 40 pixels to 100 percent, takes off the li element floats, changes the line-height, and changes the margins. Figure 7 shows an example of what the menu looks like when run on a device with a width of 320 pixels.

Figure 7: A dynamically modified navigation menu for devices with a screen width of 320 pixels


Mobile devices with a maximum width of 480 pixels need different CSS styles applied because they have 160 additional pixels of width. To do this, you can add a new CSS media query into the style sheet, as shown in Figure 8. Looking through the CSS, you'll see that only a minimal override is added to adjust the padding of anchor tags because the menu fits by default in this screen width.

@media screen and (max-width: 480px) {    nav ul > li > a {    padding: 8px 10px 7px 10px;    }}

Running the site on a device with 480 pixels will render the menu in Figure 9. Notice that the space between the menu items is much smaller compared with what was shown earlier in Figure 2.

Figure 9: Rendering the navigation menu on a device 480 pixels wide

In addition to modifying the menu, you can change the three horizontal content sections shown earlier in Figure 2 from a horizontal layout to a vertical layout, so that they look good on a variety of smaller mobile devices and can be more easily navigated by end users. The HTML5 article and section elements are used as containers for the three sections in the site, as shown in Figure 10.

        Why Choose Us?    
                Post emensos insuperabilis expeditionis eventus languentibus partium        animis, quas periculorum varietas fregerat et laborum, nondum        tubarum cessante clangore vel milite locato per stationes hibernas.                 Products    
                        Widget 1        Widget 2        Widget 3        Widget 4        Widget 5                        FAQ    
                        FAQ 1        FAQ 2        FAQ 3        FAQ 4        FAQ 5                

To force the sections into a vertical layout for smaller mobile devices, you can add the CSS styles shown in Figure 11 into the media queries targeting 320 pixel and 480 pixel widths.

@media screen and (max-width:320px) {      section {    float: none;    width: 97%;    margin: 0px;    padding: 5px;    }    #wrapper {    padding: 5px;    width: 96%;    }    #mainImage, #gearsImage, #faqImage {      width: 100%;    height: 100px;    }}@media screen and (max-width: 480px) {    section {    float: none;    width: 98%;    margin: 0px 0px 10px 0px;    padding: 5px;    }    article > section:last-child {    margin-right: 0px;    float: none;    }    #bottomSection {    width: 99%;    }    #wrapper {    padding: 5px;    width: 96%;    }    #mainImage, #gearsImage, #faqImage {    width: 100%;    height: 100px;    }}

Styles to target the display size of the images in each section are also included. It's important to note that the original image is still being downloaded from the server and isn't being optimized in any way for the mobile device. It's certainly possible for the CSS to include URL information for a mobile-optimized image, if desired.

Figure 12 and Figure 13 show the site rendered on an iPhone with the CSS media queries in place. Each of the sections now displays vertically, making it much easier for the user to access them. Images within each section also scale appropriately to fit properly.

Figure 12: Rendering the Widget Masters site on a mobile device
Figure 13: Restructured section elements and images, which are now displayed vertically instead of horizontally

More Flexibility for Your Website

CSS media queries provide a great way to override default styles in a website and target devices with different resolutions. In this article, you've seen how CSS media queries can be used to convert a standard browser-based site into a site that's more accessible to mobile users. Although much more can be done to optimize sites for mobile, CSS media queries provide a nice starting point if you don't have the time or resources to create mobile-specific versions of sites. Next, we'll show you how to utilize the techniques that you've learned to implement a responsive design interface with HTML5 and CSS3.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like