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.