Mobile site CSS with CSS3 media queries (Mobilizing websites with responsive design and HTML5 part 5)

This blog post is a part of Mobilizing websites with responsive design and HTML5 tutorial. For all posts please see the Introduction post.

To mobilize the legacy website, we create a responsive design with two layout steps: desktop and mobile. We use a separate mobile.css stylesheet which will override legacy desktop styles for mobile browsers with more suitable variations for small screens.

CSS3 Media queries are a method of selectively loading CSS stylesheets based on various criteria like screen size and orientation. They are supported by all state-of-the-art mobile and desktop browsers.

mobile.css stylesheet

  • is loaded for mobile devices only using CSS3 media queries
  • when developing, we force the file to be loaded on our development browser (Firefox + Firebug) simply by removing the media query condition in the stylesheet HTML tag

1. Defining the media query to discriminate mobile devices

The media query uses simple screen pixel count to determine whether the screen is “small” or not. Though CSS3 has rapidly advanced, it still cannot answer the basic question “what is the diameter of the screen in physical inches”, the only information which we would be interested in. Thus, some heuristics are required to guess whether the screen is actually small or not… hopefully we’ll see some kind of pixel size + DPI or diameter in inches selectors in the future CSS media queries to make hacks unnecessary.

Note: In the case related to this tutorial, the client wanted the tablet browsers to receive mobile styling also. This improved touch screen accessibility, though the tablet browsers usually work well with desktop layouts too.

Note: Media queries determine the screen width by the device orientation and you can have different CSS loaded depending whether the device is in portrait or landscape orientation mode.

Note: Browsers report their screen width in heterogeneous manner. Whether reported widths are the virtual screen width in virtual pixels or the real pixel width may vary browser by browser. See notes below.

Note: WebKit has a WebKit specific media query selector called -webkit-device-pixel-ratio which tells ratio between physical and virtual pixels. It is designed to discriminate high DPI mobile screens, which are wider than 640 pixels but still in small form factor.

CSS3 media query linking code for loading the mobile.css stylesheet in HTML <head>:

     Detect mobile devices + iPad.

     High DPI smart phones report "virtual" pixels here which is usually 1/2 x normal pixels.
     E.g. iPhone 4 with 960 px wide screen reports 480 pixels.
     We use 500 px as the threshold.

     We cut out devices at 900 pixels wide, so 1024 px desktop screens are not included.


   <link rel="stylesheet" media="screen and (max-device-width: 900px)" href="css/mobile.css" />


     This is for Android.

     Android Browser HPDI screens uses actual pixels max-device-width and
     they are indistinguishable from iPad. The screen can have max-device-width=768
     which is also the value for tablets.

     Here we simply use WebKit HDPI screen "virtual pixel" aspect ratio detector
     to see if we are using virtual pixels. If we are then assume a mobile screen.


   <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 1.5)" href="css/mobile.css" />

To test the mobile styles in a deskto browser simply remove media condition from <link> code.

The project page before mobile CSS was applied:

The page after mobile CSS has been applied:

Much better!

Note: Older mobile browsers might not support CSS3 media queries. They will simply fallback to the desktop version of the site CSS, no harm done.

Resetting desktop styles

The most important task for the mobile.css to do is to reset the website width and main content wrapping from the hardcoded centered column to something spreading across the whole mobile screen width.

Here are some example styles we applied in mobile.css to drop hardcoded width values and adjust margins to more suitable values. As you can see we use !important CSS directive to override many desktop styles – if your site is using several CSS files or complex style hierarchies this switch might be needed to make sure styles are overridden properly.

/* Disable background image */
body {
    background: white !important;

/* Fill entire mobile viewport width - don't force hard pixel widths*/
#visual-portal-wrapper {
    width: 100% !important; /* Was width: 960px */
    margin: 0;

#main-margin {
     margin: 0;

/* Mobile footer cannot be fixed height as it may layout as many rows
   instead of one */
#footer2 {
    width: 100% !important;
    margin: 0;
    padding: 0;
    height: auto; /* Was 60px */

/* Fix footer margins */
#footer-wrapper {
    padding: 10px 20px 0 20px;

/* Make two footer elements reactive and lay from top to bottom on too narrow screen */
#footer-wrapper > div {
   display: block;
   float; left;

#footer-wrapper > a {
   width: 120px;

2. More information

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

Setting mobile browser meta viewport tag (Mobilizing websites with responsive design and HTML5 part 4)

This blog post is a part of Mobilizing websites with responsive design and HTML5 tutorial. For all posts please see the Introduction post.

By default, modern mobile browsers render websites in a “virtual screen” mode (viewport) where they allocate a virtual screen wide around 900 pixel for the webpage rendering. Then the users can pinch and zoom themselves around in this viewport. The default desktop-ish viewport in mobile browsers is for the legacy reasons; non-mobile aware legacy layouts would blow up if they were fitted into a small mobile screen estate.

Pinching and zooming around is not what we want to do – it makes the browsing experience constant pain of finding the start of the next paragraph. Setting a “normalized” viewport is the first thing you do when are mobilizing a website. This tells mobile browsers that the site is mobile browser aware and the mobile browser should use the actual mobile screen dimensions instead of virtual pan and zoom screen for rendering the web page.

This happens by settings a <meta name="viewport" > tag in HTML <head> section. The tag was introduced by Apple on iOS devices and has been later adapted by other Android, Opera, Firefox mobile browsers.

Here is an example:


    Set a mobile viewport which uses actual mobile screen dimensions instead of
    a virtual screen, but still allows user to zoom in for visual impairment

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5">

This viewport tag says that

  • Use device native screen width instead of virtual screen width
  • Set scale to 1 when the page is opened
  • Allow still the user to zoom in (maximum-scale=5). Some mobile site disable pan and zoom altogether of having maximum-scale=1, but this is not recommended as a lot of elderly people like to zoom into text even if the text is very large and optimized for small screens.

Before the viewport tag was applied:

After the viewport tag has been applied:

As you can see there is a clear difference in the page rendering, but this is not definitely enough to make the site look good on mobile: the CSS styles must be fixed also as usually legacy CSS styling uses  “min-width: 960px” or similar horizontally centered main column definition. Since we don’t have that 960 pixels in mobile screens, the layout cannot work properly yet. In the next tutorial blog post we’ll show how to fix this with CSS3 media queries and CSS overriding mechanism.

Note: As the viewport tag is not very standardized yet, there exist tons of pitfalls with it. Especially if you try to dynamically edit it with Javascript you’ll get undesirable results or no change. Always inject the viewport tag on the server-side into HTML payload.

Note: The viewport tag may affect iPad and Android tablets. The desktop browsers ignore it, though. Test your mobile site with the tablet devices also.

1. More information

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

Considerations when mobilizing a legacy website (Mobilizing websites with responsive design and HTML5 part 3)

This blog post is a part of Mobilizing websites with responsive design and HTML5 tutorial. For all posts please see the Introduction post.

As mentioned in the introduction, this tutorial is based on an consulting job to mobilize a centralized user authentication system. To be exact, the system is Shibboleth federation login used by various public sector institutions. The authentication system allows users to cross-authenticate themselves across organizational borders: erg. students from a university can join to wi-fi in another universities using their existing home university logins and so on.

Since the federation login component is very central for many public sector organizations and the mobile uptake has been high during the recent years, there was pressure to get the federation login to run well on mobile devices too.

This is how the landing page looked on mobile devices before any mobilization work:

1. Applying a hint of responsiveness on an existing layout

Responsive design (a.k.a reactive layout) is a technique where the same HTML payload is adapted to different screen sizes using CSS3 media queries and optionally client side Javascripting. It is an alternative for building a separate mobile site or page.

To have the basic mobile functionality, a responsive design layout needs to have at least two distinct layout steps. The steps could be:

  • desktop: 1024 pixels and wider screens
  • small screen (mobile): 1024 pixels or smaller, possibly including tablet devices

The site we mobilized in the tutorial project was a landing page with few form elements. The design was simple: applying layout changes to achieve responsive layout was possible. However, usually migrating to responsive design techniques require designing the site layout and theme from the grounds up using mobile first approach. This is because legacy designs seldom have respected HTML philosophy and they take it granted that there is only one screen size and only one way of displaying information. Converting this kind of legacy layout to be responsive is challenging.

More info about responsive layouts

Minizing code changes and risks associated with legacy systems

When dealing with legacy codebases running in production “minimal changes” principle applies; If a system has been in production use several years, not actively maintained, every change in the codebase comes with a risk of potentially breaking something. Thus, when mobilizing a legacy website you may try to leave the existing HTML and CSS  mostly untouched using the following strategy

  • Edit HTML <head> section to support mobile devices and CSS3 media queries
  • Don’t alter the existing desktop CSS (main.css), but instead load a separate mobile specific CSS (mobile.css) and override the main CSS styles for mobile devices using the CSS overriding mechanisms (this is what Plone CMS can do with but currently sans media queries)
  • In HTML, add some missing CSS classes and wrapping <div> elements when needed, but do avoid touching functional parts

Naturally, this all apply only when you are mobilizing using responsive layout. There exist other mobilizing strategies too.

f you are re-designing the site theme from grounds up a better strategy is

  • Having a shared base.css, of which styles are applied regardless of the screen size
  • Desktop specific styles go to desktop.css which is loaded only for desktop browsers
  • Mobile specific styles go to mobile.css which is loaded only for mobile browsers

This will decrease the amount of unnecessary code loaded on mobile devices making the pages load faster.


\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

Working on HTML(5) for mobile sites (Mobilizing websites with responsive design and HTML5 part II)

This blog post is a part of Mobilizing websites with responsive design and HTML5 tutorial. For all posts please see the Introduction post.

There is no separate “mobile HTML”.

Mobile sites are normal HTML sites. Separate WAP protocol has been dead several years now. “XHTML mobile profile” is also dead. Most phones do normal HTML just fine.

Also in developing countries, where the usage of mobile Internet is more prevalent over desktop internet and the device base is geared toward feature phones with less powerful web browsers, thin client browsers like Opera Mini are widely used and support normal HTML just fine.

The major web experience considerations on mobile phones are not technical, in protocol wise. They include

  • Small screen estate
  • Lack of physical keyboard
  • Touch screen instead of mouse as a pointer device

Smartphones like iPhone, Android and Blackberry devices support new HTML5 and CSS3 features and in some cases mobile browsers are more advantaged than their desktop counter-parts. Even if you don’t like Apple as a company per se, they have done a great deal to push HTML5 forward in mobile space and taken the mobile browsing user experience from old, clumsy, WAP era to something you can actually enjoy.

1. There is no HTML5; there is only HTML

There never will be a finalized HTML5 standard and asking the question when HTML5 is ready is pointless. Browser vendors keep adapting evolving HTML features to their browsers continuously and it is up to feature detection and graceful fallbacks to determine whether you can do the trick with the browser or not.

In mobile space HTML5 features provide enhancements making the surfing experience better

  • Specialized input fields for better text input on non-hardware keyboards
  • Using CSS3 styles instead of images for layout effects; this reduces HTTP transfer payload making pages load faster
  • Touch event support
  • <video> and <audio> multimedia (as oppose to Flash)
  • etc.

2. Strategies for building a mobile site

There are several options for “mobile strategy” of your site

  • Responsive layout, as described in this tutorial
  • Using a stock mobile theme or add-on for open source CMS (Web and Mobile, WPTouch)
  • A theming HTML proxy, like Diazo, is an option when you cannot touch the front-end template source code at all. A theming proxy reads web HTML, parses it and transforms the result to new mobile HTML output based on (XSLT) rules
  • A commercial scraper which is a theming proxy with fancy UI e.g.
  • Client-side transformations with Javascript, like Mobilize.js
  • Have a separately maintained mobile site, using mobile specific CMS with information duplicated by hand or using a custom integration. Suits for large organizations where the marketing budget is big and internal communications are an issue.

What strategy you should use depends on your IT skill, organization structure and business goals. You need to balance between the wanted user experience level, budget and available competence.

3. Tools for mobile site building

Since mobile sites are normal HTML there is no need to have specific “mobile SDK” or “mobile IDE”.

When you are working on mobile HTML, excluding the device testing phase, a normal web browser fine. Use Firefox + Firebug or Chrome/Safari + developer tools. You usually don’t want to develop on mobile browsers directly, as they lack CSS inspection tools, Javascript debugger or any interaction with the HTML page source.

Note: Opera mobile browsers provide some decent HTML, CSS and Javascript remote debugging capabilities thru their Dragonfly debugging toolbar

4. Spoofing the development browser as mobile

When mobilizing a web site with responsive design, the only trick you usually need to pull is to shortcut the responsive CSS loading so that the development browser loads the mobile stylesheets.

You can do this in your own code level: instead of selectively load mobile.css file force it to be loaded in the desktop browser too by hardcoding mobile.css to be loaded for all browsers.

You could include a server-side conditions which allow you to perform the spoofing using an URL parameter:

On Javascript level touch events might also needs spoofing.

Note: It is not worth of doing mobile development using Internet Explorer as the development browser. Microsoft has recently improved their track record regarding open web standards, but they still have few years catch up to do in order to be able to match the pace of the competition.

5. User agent detection

User agent is a HTTP request header which the web browser uses to tell the web server the software version the web browser is running.

User agent detection is a method of discriminating mobile devices on the server-side and serving them a different HTML payload. I strongly discourage using this old and deprecated method of mobilization in the contemporary world unless you really really have to.

  • The philosophy of HTML is to let the client device decide how to display the information, not the web server to guess how. Today mobile devices support enough Javascript to make it possible.
  • User agent detection is fragile, because the user agent strings themselves are a mess and different devices may have the same user agent or the same devices different user agent: false positives ensure
  • You need to maintain a server-side database of devices and the quality of available databases leaves room for improvement
  • Different HTML payloads varying by user agents destroy front-end caching performance, as there are thousands of device types and each would create its own front-end caching entry
  • It seems that widely spread, semi-open, device database project Wurlf is alienating its users

If you need to have different code paths for mobile devices then use something like detectmobile.js which performs the mobile feature detection on the client-side, effectively replacing 5 MB user agent string database with 100 lines of Javascript.

6. Native apps

A native application is nowadays almost synonym for “embedded WebKit” – unless you are doing some really high profile applications. The apps are out of the scope of this tutorial.

If you need to wrap your mobile site for App Store, Android Market, etc. distribution you can use PhoneGap. The user experience is not as great as building expensive 100% native application from the scratch, but the price tag is usually something you can swallow easier.

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+