Optimizing webpages for mobile devices, part 2: CSS media queries, Javascript and mobile-specific websites

In part 1 of this article we went over the viewport meta tag. Although it can be useful in certain circumstances I feel that it is often unecessary. What’s worse, it’s hard to predict how it will behave on different browsers and it can in fact ruin some users’ experiences if not used very carefully.

If you really want your webpage to be able to transform itself to suit mobiles, as well as various other types of devices and specific features, you can  add special CSS rules that will automatically be applied to suit the situation. This can be done either with media queries or Javascript.

Lastly, if you prefer to create a completely separate webpage for mobile devices, you’re covered there too.  Mobile-specific websites are very popular and definitely worth considering as part of your strategy.

Media Queries

Media queries have become a very popular way of optimizing webpages for mobile devices since their introduction with the advent of CSS3. They work by telling a browser to apply special CSS rules depending on the type of device a webpage is accessed from and what media features it has. As you might have inferred from the previous sentence media queries, unlike the viewport meta tag, influence not only mobile devices, but also “regular” computers (heron referred to as “desktops”), printers, and anything else that can display the webpage.

Media queries can, for example, tell a browser to use a specific stylesheet for a webpage when it detects that it is being accessed from the “printer” media type (this happens when the browser is told to print the page). That stylesheet could remove ads and background images, for instance.

Below is an example of a media query that displays a webpage’s background in different colors depending on the “width” feature. This feature corresponds to the width of the browser window.

Media queries

As with “normal” CSS, media queries can be defined in several ways. However unlike regular CSS selectors, media queries cannot be defined inline in an HTML tag. The ways in which we can refer to media queries are:

  • From inside the document in which they will be used. As shown below, the code should be enclosed by the <style> tags, which in turn are enclosed by the <head> tags.

<head>
     <style type=”text/css”>
@media screen and (max-width: 480px) {
selector { property: value; }
}
     </style>
</head>

While the page has a maximum width of 480 pixels it will follow the rules inside the bracketes (selector { property: value; })

  • From an external stylesheet by importing said stylesheet into the document in which it will be used using the <style> tags. Again, the code should be enclosed by the <style> tags, which in turn are enclosed by the <head> tags. 
    • @import rules must always be placed before any other CSS content, including comments. They are not supported by really, really old browsers.

<head>
<style type=”text/css”>
          @import “480pxRules.css” screen and (max-width:        480px);
</style>
</head>

While the page has a maximum width of 480 pixels it will follow the rules defined in “480pxRules.css.”

  • From an external stylesheet by importing a stylesheet into the document in the “regular” manner using the <link> tag enclosed by the <head> tags. With this method media queries will be handled by the imported stylesheet instead of the document. The imported stylesheet can contain any combination of the two methods above (the parts which are in bold), and of course regular CSS.  Two things to note:
    • Remember that @import rules must be placed before any other CSS content and are not supported by very old browsers.
    • Rules of selectors that appear more than once are always overriden by the last definition. This means that media queries should always appear after all other CSS.
    • As a result of the above two rules any CSS imported into a document must not contain selectors that are repeated in said document or later import.

<head>
<link rel=”stylesheet” type=”text/css” media=”screen” href=”style.css” />
</head>

This is a usual stylesheet import. Testing for page width and applying the corresponding CSS rules is done either in “style.css” or in other stylesheets imported into “style.css.”

  • From an external stylesheet by importing said stylesheet into the document in which it will be used using the <link> tag. The code should be enclosed by the <head> tags.

<head>
     <link rel=”stylesheet” type=”text/css”      href=”480pxRules.css” media=”screen and (max-width: 480px)” />
</head>

While the page has a maximum width of 480 pixels it will follow the rules defined in “480pxRules.css.”

Although the different ways of referring to media queries might cause some confusion due to their different syntaxes, the overall “template” should make sense to anyone well versed in CSS. In any case, it’s just a matter of deciding which method to call the queries with and sticking to that general template while modifying media types and detectable media features to suit the situation. These variables are defined as such:

  • Media types: used to specify which type(s) of media the CSS rules will apply to. For example, in the examples above I have used the “screen” media type, which was primarily meant for color computer screens. However this media type also targets most smartphones nowadays, despite the fact that there also exists a “handheld” media type. If you don’t care about old “handheld” devices it’s enough to set your media type to “screen.” If you want to be safe, set it to “screen, handheld.” By leaving out media types entirely the CSS rules you define will apply to all media types. Here is W3C’s guide to media types and an article on the doomed “handheld” media typePro tip: instead of driving yourself crazy with 10 different stylesheets for each media type, focus on “screen” and possibly “print,” which are the two most used and useful media types.
  • Detectable media features: the most important part of media queries, these are the conditions we can screen for. “Max-width” and “min-width” are the most useful for our purposes; possibly also “orientation.” As with the viewport meta tag, each “width” variant has different uses when optimizing for mobile devices, but since media queries also apply to desktops, you will probably want to avoid the ones which refer to device-width, which always returns the resolution of the device. That’s fine for mobile devices since the browser usually takes up the entire screen space but if the user is on a desktop  it will return that device’s resolution regardless of the current window size. On the other hand “width,” “min-width” and “max-width” always return the width of the browser window.1

There is actually one last component that is very important. Don’t worry, it’s an easy one:

  • Logical operators: allows screening for both media type and multiple media features using the notand, and only operators. For example, “min-width” and “max-width” can be used together to specify that the CSS rules are only to be used when the window is between two different widths:

<head>
<link rel=”stylesheet” type=”text/css” href=”480to900pxRules.css” media=”screen and (min-width: 480px) and (max-width: 900px)” />
</head>

1 Media queries that refer to device-width are relevant if you actually want mobile devices to use different CSS rules than desktops. My HTC Desire has a resolution of 480px, which is the most common resolution for smartphones. CSS rules set for “max-device-width: 480px” will affect my Desire and most other smartphones. Desktop browsers would not be affected by these rules unless the actual screen monitor was 480 pixels wide, an uncommon sight to say the least. 

Javascript

Media queries are not the only way of specifying CSS rules based on different media types or features. Basically by using Javascript to get a desired value (width, for example) and then feeding them it into a specific function we can assign different CSS rules to differently sized windows and devices. That’s beyond the scope of this article, but Particletree wrote a very good article about it over 7 years ago! It is definitely worthy of consideration. With that thought, following are the pros and cons of both media queries and Javascript. I can’t recommend one or the other; read about both and pick what’s right for you!

Advantages of CSS media queries

  • Do not require Javascript to be enabled in the user’s browser.
  • Browsers that support CSS2 and CSS3 all interpret detection of media features and media types in the same way.

Disadvantages of CSS media queries

  • Detectable media features are CSS3, which means older browsers may not support them (media types were introduced in CSS2 so they have wider browser support).
  • As Rob Glazebrook pointed out in his article Using the CSS @import Rule Internet Explorer versions 4-7 cannot handle media types correctly. Still no confirmation if they work on IE8. Leave a comment if you’ve got the answer!
  • All CSS is loaded upon page load even if the conditions on which it depends are never met.

Advantages of Javascript

  • Older browsers that do not support CSS2 media types or CSS3 detectable media features can handle all of that through Javascript.
  • Allows checking for media types and features before loading the corresponding CSS files (assuming that CSS is not defined in the same document). This keeps unecessary CSS files from loading, but the Javascript itself slows down page loading. The conclusion is that this point is only relevant when every second counts, and then only if the amount of CSS to load for different situations is large enough that it pays off having the extra Javascript.

Disadvantages of Javascript

  • Users must have Javascript enabled in their browser.
  • Different browsers detect media features using different object/property combinations. According to Craig Buckler at Sitepoint “all the main browsers support document.documentElement.clientWidth anddocument.documentElement.clientHeight but it’s inconsistent. Either the window or document dimensions will be returned depending on the browser and mode.”
  • When the amount of special CSS rules is small, the extra Javascript doesn’t pay off with regards to page load times.

Mobile-specific websites

Because of the huge potential media queries and Javascript have in allowing you to control how your webpages are displayed under different circumstances, I would recommend getting familiar with and making use of them. At the same time it can be easy to get overwhelmed by the amount of possibilities. That’s never good, so if your aim is simply to create a good mobile experience to match what you’ve created for desktop users, a mobile-specific website just might be the answer.

As you might have guessed a mobile-specific website is completely separate from the main website, although it is usually a sub-domain of that site (for example, m.yourdomain.com). Everytime someone visits the main domain name (yourdomain.com), a function runs and checks what kind of device it’s being accessed from and then re-directs them to the appropriate site.

The code which checks the device type can be written in a variety of languages. Javascript is popular for this application but if your server supports a server-side language I would recommend that to ensure that it will work for all users. If you don’t want to write your own code I’ve come across a very nice solution called WURFL. What’s awesome about it is that it uses a “repository” (wurfl.xml), which contains the definitions of thousands of devices, and is constantly being updated. On their website it is stated that “WURFL is deployed by key Internet companies such as Facebook and Google” so I can’t imagine that there is a more effective way to do device detection, but I haven’t actually tried it myself. There are APIs available in several programming languages or you could write your own and just use their wurfl.xml file.

Conclusion

The viewport meta tag, media queries, Javascript, and mobile-specific websites — and that’s not to mention good design sense! With so many options and a growing number of users accessing webpages through iPhones, Android phones, tablets and other mobile devices there is no excuse not to give your visitors a great experience everytime.

Optimizing webpages for mobile devices, part 1: viewports and the viewport meta tag

Do you own an iPhone? How about an Android phone? iPad? There is a good chance that you or someone you know does. With more and more people using  smartphones and other mobile devices to browse the internet it is imperative that you as a web designer take a moment to consider your mobile users. If you haven’t been optimizing your pages for different desktop resolutions, that is usually the best place to start and may in fact be all you need to do. If you need to go deeper there are several options:

  • Use the viewport meta tag.
  • Screen for different window/device sizes and target them with specific CSS rules (media queries or Javascript).
  • Screen for mobile devices and present them with mobile-specific pages.

This is part 1 of a 2-part article on mobile device optimization, where we will also discuss different monitor resolutions and screen sizes on desktop and laptop computers (hereon referred as “desktop”).

Read on to find the advantages and disadvantages of optimizing your webpages, learn about viewports and how to use the viewport meta tag. In part 2 we will go over media queries, Javascript and mobile-specific websites.

You don’t have to optimize for mobile devices

If you don’t have the time or desire to optimize your webpage for mobile devices, you can rest assured that it will display fine on mobile devices as long as:

OR

  • All of your layout and content is inside a container or wrapper with a fixed width, such as a <div>. This <div> would set your viewport width ( more on viewports later).

If you’re not sure if you meet one of these requirements you can easily test how your page will look on a mobile device by shrinking your desktop browser window to simulate a smaller display. If everything looks good then you can stop there if you want. It doesn’t even matter if you have to scroll horizontally to see everything; the point is to check that your layout doesn’t fall apart on a resized browser window or a small mobile display.

If your design doesn’t hold upon resizing the browser window, you should probably work on it some more. You could add a viewport meta tag with a fixed width to fix the problem for mobiles, as we will see later, but it’s no fun for your users to see a mess when they resize the window on their desktop either.

How does it look?

Regardless of how your layout looks upon resizing, be aware that if it has a set width that is too wide for a particular display most mobile browsers will automatically zoom out in order to fit everything on the screen. Otherwise useres can zoom out themselves, though you can limit that option in the viewport meta tag which, again, we will explore later.1 The point is to keep this in mind since your zoomed out webpage might look very small depending on the mobile device.2

1 The concept is the same for desktop browsers: if you have to scroll horizontally the layout is too wide for your display. You’re free to zoom out instead of scrolling. 

2 You can test this pretty accurately by placing your mobile device up against your desktop monitor (or using a physical ruler to measure for other screen sizes) and resizing your browser window horizontally so that it is the same width as the mobile display. Then zoom out until the horizontal scroll bars disappear. You might get strange looks while you’re doing this, but you can just ignore that or tell them that you’re doing it for science! What you see on your desktop browser now should correspond to what gets displayed on the mobile device, but be aware that it might be slightly off since your browser probably doesn’t allow such surgical zooming. Also when text and images are so small they might not render with the same quality as they would on the mobile device.

Pros of leaving your pages unoptimized

Assuming you have a fluid design or all of your layout and content is inside a container (wrapper) with a fixed width…

  • Takes absolutely no time and zero effort.
  • Retains the same design users see on their desktop browser.

Cons of being lazy

Assuming you don’t have a fluid (liquid) design or if the layout/content is not inside a container (wrapper) with a fixed width…

  • Layouts which have a set width considered “normal” on a desktop display will be too wide for most mobile devices. This will in turn make it necessary for users to zoom in and out in order to juggle between seeing the entire page and actually being able to see any one thing in a reasonable amount of detail.

The viewport and the viewport meta tag

It can be tricky deciding how or if you should even use the viewport meta tag. And if you do decide to use it, should you combine it with the other mobile optimization tools at your disposal? In the following paragraphs I will attempt to answer these and other questions that you will inevitably ask yourself.

In order to understand what the viewport meta tag does you should first know what a viewport is. Simply put, the viewport is the area which contains your entire page. Everything you see on your browser window you are seeing through the viewport.

On a desktop browser you might have to scroll up and down or side to side to see everything. Most mobile browsers will not show you scroll bars but will instead let you zoom in and out to see the entire page.  Regardless of how much you are shown when the page first loads, the entire area in which you can move around is enclosed by the viewport.

Viewports
Viewports and zoom (click to enlarge)
Most mobile browsers automatically load pages zoomed out (right) so that the entire viewport is visible, but you can have a certain amount of control over this by setting initial-scale or minimal-scale values in your viewport meta tag.

——————————–

So now you might be wondering how to control the size of the viewport. If it has not been set by an element, as described earlier, we can go ahead and insert the infamous viewport meta tag between the <head> tags on the page.3 It looks like this:

<meta name=”viewport” />

It’s not much to look at and it is in fact useless as defined above. In order to control anything with this tag we need to add some parameters to it. To set a specific width to our viewport we could write:

<meta name=”viewport” content=”width=1500″ />

And here it is again with even more parameters:

<meta name=”viewport” content=”width=1500,initial-scale = 1.0,maximum-scale = 1.0″ />

In this case we are telling the browser to make the viewport 1500 pixels wide (width=1500). The page is loaded at 100% zoom (initial-scale=1.0) and the user is not allowed to zoom in (maximum-scale=1.0).

One last example:

<meta name=”viewport” content=”width=1500,initial-scale = 1.0,minimum-scale = 1.0″ />

This time the user is not allowed to zoom OUT (minimum-scale=1.0). Combined with the other values we provided this is probably not a good idea: since 1500 pixels is a lot for most mobile displays and the page is being loaded at 100% zoom the user will only see the top-left corner of the page on most mobile devices. Combine that with the inability to zoom out and the user will have a very frustrating experience!

3 Remember that the viewport meta tag has no effect on desktop browsers. It can be useful in controlling how your page displays on mobile devices, but if your layout falls apart when you resize the browser window on a desktop you should fix that first. 

What can you do with the viewport meta tag?

Below are several things you can do to control how the viewport is presented to users. Keep in mind that different combinations of meta tag parameters can produce different results, which are often hard to predict. On top of that different browsers may have different ways of interpreting parameters and their values so the more browsers a page is tested on, the better.

Note for parameters that take numerical values that these should not be less than “1.0” (100%) as different browsers either ignore or output unpredictable results for lower values. By the same token manually zooming out to less than 100%  does not seem possible.

  • Control the width of the viewport using the width parameter.
    • “width=x” for a viewport x pixels wide or “width=device-width” to let devices set viewport width automatically. This page lists many mobile devices and their default viewport sizes.
    • “width=device-width” is a good choice for liquid and responsive designs as it ensures that the page loads at 100% zoom, meaning a comfortable reading experience across devices.
    • The width parameter may override a viewport width previously defined by an element or vice-versa depending on the browser.
    • If no width is defined by a page element or by the viewport meta tag, different browsers will set different viewport widths.
    • The width parameter has corresponding “height” and “device-height” values but in most cases it is not useful to control viewport height.
  • Set the initial zoom level of a page when it loads using the initial-scale parameter.
    • “initial-scale=x” sets page width to (x*100)%, then disables the ability to zoom out if no element exists with a wider width. Otherwise zoom out limits vary by browser or are limited by the minimum-scale parameter.
    • 100% zoom corresponds to the device’s default viewport size.
    • initial-scale may override minimum-scale and/or maximum-scale or vice-versa depending on the browser.
  • Limits how much users are allowed to zoom IN using the maximum-scale parameter.
    • “maximum-scale=1.0” disables the ability to zoom in, higher numbers allow zooming in more.
  • Limits how much users are allowed to zoom OUT using the minimum-scale parameter.
    • “minimum-scale=x” sets page width to (x*100)% , then disables the ability to zoom out since it is already at the minimum scale of (x*100)%.
    • minimum-scale may override initial-scale or vice-versa depending on the browser.
  • Control whether users are allowed to zoom in and out in your page using the user-scalable parameter.
    • “user-scalable=yes” allows users to zoom in and out; “user-scalable=no” disallows zooming in and out.
    • The most unpredictable parameter of the viewport meta tag is the user-scalable parameter and its use is strongly disencouraged. Despite previously defined viewport widths, some browsers set unique viewport widths on page load when user-scalable is set to “no.” Additionally all other parameters of the viewport meta tag are disabled, effectively denying not only the user but also the developer the ability of scaling and controlling the page layout. Many browsers do not support the user-scalable parameter.
    • The default value of the user-scalable parameter is “yes.” To disallow users the ability of zooming in and out the best option is to set “maximum-scale=1.0, minimum-scale=1.0”

Some examples of defining viewport width

Following are three different ways to set the viewport width on a page, plus one example where no width is set anywhere. Examples are meant to be viewed on a mobile device — view the index page at goo.gl/ma4Fm or scan the following QR code:
Viewport width test

When should you use the viewport meta tag?

  • When you have a layout that already works well on a desktop — including when the resolution is low or the browser window is small — and you want to have more control over how the page is displayed on mobile devices.

When should you refrain from using the viewport meta tag?

  • When your design is falling apart when viewed on lower desktop resolutions and resized browsers. The viewport meta tag only applies to mobile devices; therefore it is important to fix these problems at their source so that your desktop users (which is probably the marjority) also have a decent experience.
  • When you cannot test your webpage on multiple mobile browsers. Since different browsers handle viewport meta tag parameters differently what works on one browser may give a completely different result on another.

Conclusion

In a lot of ways optimizing for mobile devices is the same as making sure that your pages work on different desktop resolutions and resized browsers — something webdesigners have been doing since the dawn of time. Many of the old tricks can still be used and we can now combine them with new tools whose development was encouraged by the evergrowing use of the internet on small screens. In addition new solutions like the viewport meta tag, CSS media queries and mobile-specific websites have been exclusively developed to deal with mobile devices.

Part 2: media queries, a Javascript alternative to media queries, and mobile-specific websites.