Skip navigation
Help

Smashing Magazine

warning: Creating default object from empty value in /var/www/vhosts/sayforward.com/subdomains/recorder/httpdocs/modules/taxonomy/taxonomy.pages.inc on line 33.
Original author: 
Stéphanie Walter

  

Responsive Web design has been around for some years now, and it was a hot topic in 2012. Many well-known people such as Brad Frost and Luke Wroblewski have a lot of experience with it and have helped us make huge improvements in the field. But there’s still a whole lot to do.

In this article, we will look at what is currently possible, what will be possible in the future using what are not yet standardized properties (such as CSS Level 4 and HTML5 APIS), and what still needs to be improved. This article is not exhaustive, and we won’t go deep into each technique, but you’ll have enough links and knowledge to explore further by yourself.

The State Of Images In Responsive Web Design

What better aspect of responsive Web design to start off with than images? This has been a major topic for a little while now. It got more and more important with the arrival of all of the high-density screens. By high density, I mean screens with a pixel ratio higher than 2; Apple calls these Retina devices, and Google calls them XHDPI. In responsive Web design, images come with two big related challenges: size and performance.

Most designers like pixel perfection, but “normal”-sized images on high-density devices look pixelated and blurry. Simply serving double-sized images to high-density devices might be tempting, right? But that would create a performance problem. Double-sized images would take more time to load. Users of high-density devices might not have the bandwidth necessary to download those images. Also, depending on which country the user lives in, bandwidth can be pretty costly.

The second problem affects smaller devices: why should a mobile device have to download a 750-pixel image when it only needs a 300-pixel one? And do we have a way to crop images so that small-device users can focus on what is important in them?

Two Markup Solutions: The <picture> Element and The srcset Attribute

A first step in solving the challenge of responsive images is to change the markup of embedded images on an HTML page.

The Responsive Images Community Group supports a proposal for a new, more flexible element, the <picture> element. The concept is to use the now well-known media queries to serve different images to different devices. Thus, smaller devices would get smaller images. It works a bit like the markup for video, but with different images being referred to in the source element.

The code in the proposed specification looks like this :


<picture width="500"  height="500">     
  <source  media="(min-width: 45em)" src="large.jpg">
  <source  media="(min-width: 18em)" src="med.jpg">
  <source  src="small.jpg">
  <img  src="small.jpg" alt="">
  <p>Accessible  text</p>
</picture>

If providing different sources is possible, then we could also imagine providing different crops of an image to focus on what’s important for smaller devices. The W3C’s “Art Direction” use case shows a nice example of what could be done.

Picture element used for artistic direction
(Image: Egor Pasko)

The solution is currently being discussed by the W3C Responsive Images Community Group but is not usable in any browser at the moment as far as we know. A polyfill named Picturefill is available, which does pretty much the same thing. It uses a div and data-attribute syntax for safety’s sake.

A second proposal for responsive images markup was made to the W3C by Apple and is called “The srcset Attribute”; its CSS Level 4 equivalent is image-set(). The purpose of this attribute is to force user agents to select an appropriate resource from a set, rather than fetch the entire set. The HTML syntax for this proposal is based on the <img> tag itself, and the example in the specification looks like this:


<img  alt="The Breakfast Combo" 
  src="banner.jpeg"
  srcset="banner-HD.jpeg  2x, banner-phone.jpeg 100w, banner-phone-HD.jpeg 100w 2x">

As you can see, the syntax is not intuitive at all. The values of the tag consist of comma-separated strings. The values of the attribute are the names or URLs of the various images, the pixel density of the device and the maximum viewport size each is intended for.

In plain English, this is what the snippet above says:

  • The default image is banner.jpeg.
  • Devices that have a pixel ratio higher than 2 should use banner-HD.jpeg.
  • Devices with a maximum viewport size of 100w should use banner-phone.jpeg.
  • Devices with a maximum viewport size of 100w and a pixel ratio higher than 2 should use banner-phone-HD.jpeg.

The first source is the default image if the srcset attribute is not supported. The 2x suffix for banner-HD.jpeg means that this particular image should be used for devices with a pixel ratio higher than 2. The 100w for banner-phone.jpeg represents the minimum viewport size that this image should be used for. Due to its technical complexity, this syntax has not yet been implemented in any browser.

The syntax of the image-set() CSS property works pretty much the same way and enables you to load a particular background image based on the screen’s resolution:


background-image: image-set(  "foo.png" 1x,
  "foo-2x.png"  2x,
  "foo-print.png"  600dpi );

This proposal is still a W3C Editor’s Draft. For now, it works in Safari 6+ and Chrome 21+.

Image Format, Compression, SVG: Changing How We Work With Images on the Web

As you can see, these attempts to find a new markup format for images are still highly experimental. This raises the issue of image formats themselves. Can we devise a responsive solution by changing the way we handle the images themselves?

The first step would be to look at alternative image formats that have a better compression rate. Google, for example, has developed a new image format named WebP, which is 26% smaller than PNG and 25 to 34% smaller than JPEG. The format is supported in Google Chrome, Opera, Yandex, Android and Safari and can be activated in Internet Explorer using the Google Chrome Frame plugin. The main problem with this format is that Firefox does not plan to implement it. Knowing this, widespread use is unlikely for now.

Another idea that is gaining popularity is progressive JPEG images. Progressive JPEG images are, as the name suggests, progressively rendered. The first rendering is blurry, and then the image gets progressively sharper as it renders. Non-progressive JPEG images are rendered from top to bottom. In her article “Progressive JPEGs: A New Best Practice,” Ann Robson argues that progressive JPEGs give the impression of greater speed than baseline JPEGs. A progressive JPEG gives the user a quick general impression of the image before it has fully loaded. This does not solve the technical problems of performance and image size, though, but it does improve the user experience.

Another solution to the problems of performance and image size is to change the compression rate of images. For a long time, we thought that enlarging the compression rate of an image would damage the overall quality of the image. But Daan Jobsis has done extensive research on the subject and has written an article about it, “Retina Revolution.” In his experiments, he tried different image sizes and compression rates and came up with a pretty interesting solution. If you keep the image dimensions twice the displayed ones but also use a higher compression rate, then the image will have a smaller file size than the original, but will still be sharp on both normal and high-density screens. With this technique, Jobsis cut the weight of the image by 75%.

Image compression example
Daan Jobsis’ demonstration of image compression.

Given the headaches of responsive images, the idea of gaining pixel independence from images wherever possible is seducing more and more designers and developers. The SVG format, for example, can be used to create all of the UI elements of a website and will be resolution-independent. The elements will scale well for small devices and won’t be pixellated on high-density devices. Font icons are another growing trend. They involve asigning icon glyphs to certains characters of the font (like the Unicode Private Area ones), giving you the flexibility of fonts. Unfortunately, the solution doesn’t work with pictures, so a viable markup or image format is eagerly expected.

Responsive Layout Challenge: Rearrange And Work With Content Without Touching the HTML?

Let’s face it, the fluid grids made of floats and inline blocks that we use today are a poor patch waiting for a better solution. Working with layout and completely rearranging blocks on the page for mobile without resorting to JavaScript is a nightmare right now. It’s also pretty inflexible. This is particularly significant on websites created with a CMS; the designer can’t change the HTML of every page and every version of the website. So, how can this be improved?

Four CSS3 Layout Solutions That Address the Flexible Layout Problem

The most obvious possible solution is the CSS3 flexible box layout model (or “flexbox”). Its current status is candidate recommendation, and it is supported in most major mobile browsers and desktop browsers (in IE starting from version 10). The model enables you to easily reorder elements on the screen, independent of the HTML. You can also change the box orientation and box flow and distribute space and align according to the context. Below is an example of a layout that could be rearranged for mobile. The syntax would look like this:


.parent {
  display: flex;
  flex-flow: column; /* display items in columns */
}

.children {
  order: 1; /* change order of elements */
}

Flexbox as an example

The article “CSS3 Flexible Box Layout Explained” will give you a deeper understanding of how flexbox works.

Another solution quite close to the flexbox concept of reordering blocks on the page, but with JavaScript, is Relocate.

A second type of layout that is quite usable for responsive design today is the CSS3 multiple-column layout. The module is at the stage of candidate recommendation, and it works pretty well in most browsers, expect for IE 9 and below. The main benefit of this model is that content can flow from one column to another, providing a huge gain in flexibility. In terms of responsiveness, the number of columns can be changed according to the viewport’s size.

Setting the size of the columns and letting the browser calculate the number of columns according to the available space is possible. Also possible is setting the number of columns, with the gaps and rules between them, and letting the browser calculate the width of each column.

CSS3 Multiple Column layout

The syntax looks like this:


.container {
  column-width: 10em ; /* Browser will create 10em columns. Number of columns would depend on available space. */
}

.container {
  columns: 5; /* Browser will create 5 columns. Column size depends on available space. */
  column-gap: 2em;
}

To learn more, read David Walsh’s article “CSS Columns.”

A third CSS3 property that could gain more attention in future is the CSS3 grid layout. This gives designers and developers a flexible grid they can work with to create different layouts. It allows content elements to be displayed in columns and rows without a defined structure. First, you would declare a grid on the container, and then place all child elements in this virtual grid. You could then define a different grid for small devices or change the position of elements in the grid. This allows for enormous flexibility when used with media queries, changes in orientation and so on.

The syntax looks like this (from the 2 April 2013 working draft):


 .parent {
   display: grid; /* declare a grid */
   grid-definition-columns: 1stgridsize  2ndgridsize …;
   grid-definition-rows: 1strowsize  2ndrowsize …;
}

.element {
   grid-column: 1; 
   grid-row: 1
}

.element2 {
   grid-column: 1; 
   grid-row: 3;
}

To set the sizes of columns and rows, you can use various units, as detailed in the specification. To position the various elements, the specification says this: “Each part of the game is positioned between grid lines by referencing the starting grid line and then specifying, if more than one, the number of rows or columns spanned to determine the ending grid line, which establishes bounds for the part.”

The main problem with this property is that it is currently supported only in IE 10. To learn more about this layout, read Rachel Andrew’s “Giving Content Priority With CSS3 Grid Layout.” Also, note that the specification and syntax for grid layouts changed on 2 April 2013. Rachel wrote an update on the syntax, titled “CSS Grid Layout: What Has Changed?

The last layout that might become useful in future if implemented in browsers is the CSS3 template layout. This CSS3 module works by associating an element with a layout “name” and then ordering the elements on an invisible grid. The grid may be fixed or flexible and can be changed according to the viewport’s size.

The syntax looks like this:


.parent {
   display: "ab"
            "cd" /* creating the invisible  grid */
}

.child1 {
   position: a;
}

.child2 {
   position: b;
}

.child3 {
   position: c;
}

.child4 {
   position: d;
} 

This renders as follows:

CSS3 template layout

Unfortunately, browser support for this CSS3 module is currently null. Maybe someday, if designers and developers show enough interest in this specification, some browser vendors might implement it. For the moment, you can test it out with a polyfill.

Viewport-Relative Units and the End of Pixel-Based Layout

Viewport-based percentage lengths — vw, vh, vm, vmin and vmax — are units measured relative to the dimensions of the viewport itself.

One vw unit is equal to 1% of the width of the initial containing block. If the viewport’s width is 320, then 1 vw is 1 × 320/100 = 3.2 pixels.

The vh unit works the same way but is relative to the height of the viewport. So, 50 vh would equal 50% of the height of the document. At this point, you might wonder what the difference is with the percentage unit. While percentage units are relative to the size of the parent element, the vh and vw units will always be relative to the size of the viewport, regardless of the size of their parents.

This gets pretty interesting when you want to, for example, create a content box and make sure that it never extends below the viewport’s height so that the user doesn’t have to scroll to find it. This also enables us to create true 100%-height boxes without having to hack all of the elements’ parents.

The vmin unit is equal to the smaller of vm or vh, and vmax is equal to the larger of vm or vh; so, those units respond perfectly to changes in device orientation, too. Unfortunately, for the moment, those units are not supported in Android’s browser, so you might have to wait a bit before using them in a layout.

A Word on Adaptive Typography

The layout of a website will depend heavily on the content. I cannot conclude a section about the possibilities of responsive layout without addressing typography. CSS3 introduces a font unit that can be pretty handy for responsive typography: the rem unit. While fonts measured in em units have a length relative to their parent, font measured in rem units are relative to the font size of the root element. For a responsive website, you could write some CSS like the following and then change all font sizes simply by changing the font size specified for the html element:


html {
   font-size: 14px;
}

p {
   font-size: 1rem /* this has 14px */
}

@media screen and (max-width:380px) {
   html {
      font-size: 12px; /* make the font smaller for mobile devices */
   }

   p {
      font-size: 1rem /* this now equals 12px */
   }
}

Except for IE 8 and Opera mini, support for rem is pretty good. To learn more about rem units, read Matthew Lettini’s article “In Defense of Rem Units.”

A Better Way To Work Responsively With Other Complex Content

We are slowly getting better at dealing with images and text in responsive layouts, but we still need to find solutions for other, more complex types of content.

Dealing With Forms on a Responsive Website

Generally speaking, dealing with forms, especially long ones, in responsive Web design is quite a challenge! The longer the form, the more complicated it is to adapt to small devices. The physical adaptation is not that hard; most designers will simply put the form’s elements into a single column and stretch the inputs to the full width of the screen. But making forms visually appealing isn’t enough; we have to make them easy to use on mobile, too.

For starters, Luke Wroblewski advises to avoid textual input and instead to rely on checkboxes, radio buttons and select drop-down menus wherever possible. This way, the user has to enter as little information as possible. Another tip is not to make the user press the “Send” button before getting feedback about the content of their submission. On-the-fly error-checking is especially important on mobile, where most forms are longer than the height of the screen. If the user has mistyped in a field and has to send the form to realize it, then chances are they won’t even see where they mistyped.

In the future, the new HTML5 form inputs and attributes will be a great help to us in building better forms, without the need for (much) JavaScript. For instance, you could use the required attribute to give feedback about a particular field on the fly. Unfortunately, support for this on mobile devices is poor right now. The autocomplete attribute could also help to make forms more responsive.

A mobile phone is a personal possession, so we can assume that data such as name and postal address will remain consistent. Using the autocomplete HTML5 attribute, we could prefill such fields so that the user doesn’t have to type all of that information over and over. There is also a whole list of new HTML5 inputs that can be used in the near future to make forms more responsive.

Dates in form elements are a good example of what can be improved with HTML5. We used to rely on JavaScripts to create date-pickers. Those pickers are quite usable on big desktop screens but very hard to use on touch devices. Selecting the right date with a finger is difficult when the touch zones are so small.

Different picker examples
How am I supposed to select a date when my finger is touching three dates at the same time?

A promising solution lies in the new HTML5 input type="date", which sets a string in the format of a date. The HTML5 input type="datetime" sets a string in the format of a date and time. The big advantage of this method is that we let the browser decide which UI to use. This way, the UI is automatically optimized for mobile phones. Here is what an input type="date" looks like on the desktop, on an Android phone and tablet (with the Chrome browser), and on the iPhone and iPad.

Mobile input type=date rendering
Renderings of input type="date" on different mobile devices.

Note that the screenshots were taken in my browser and on the Android phone, so the language automatically adapted to the system language (French). By using native components, you no longer have to adapt the language into different versions of the website.

For now, support for input type="date" on the desktop is absent except in Opera and Chrome. Native Android browsers don’t support it at all, but Chrome for Android does, and so does Safari on iOS. A lot still has to get done in order for us to be able to use this solution on responsive websites. Meanwhile, you could use a polyfill such as Mobiscroll for mobile browsers that don’t support it natively.

Apart from these HTML5 input solutions, attempts have been made to improve other design patterns, such as passwords on mobile and complex input formatting using masks. As you will notice, these are experimental. The perfect responsive form does not exist at the moment; a lot still has to be done in this field.

Dealing With Tables on a Responsive Website

Another content type that gets pretty messy on mobile and responsive websites is tables. Most table are oriented horizontally and present a lot of data at once, so you can see how getting it right on a small screen is pretty hard. HTML tables are fairly flexible — you can use percentages to change the width of the columns — but then the content can quickly become unreadable.

No one has yet found the perfect way to present tables, but some suggestions have been made.

One approach is to hide what could be considered “less important” columns, and provide checkboxes for the user to choose which columns to see. On the desktop, all columns would be shown, while on mobile, the number of columns shown would depend on the screen’s size. The Filament Group explains this approach and demonstrates it in one of its articles. The solution is also used in the table column toggle on jQuery Mobile.

Responsive table examples
Some examples of responsive tables.

A second approach plays with the idea of a scrollable table. You would “pin” a single fixed-size column on the left and then leave a scroll bar on a smaller part of the table to the right. David Bushell implements this idea in an article, using CSS to display all of the content in the <thead> on the left side of the table, leaving the user to scroll through the content on the right. Zurb uses the same idea but in a different way for its plugin. In this case, the headers stay at the top of the table, and the table is duplicated with JavaScript so that only the first column is shown on the left, and all other columns are shown on the right with a scroll bar.

Responsive table overflow example
Two examples of scrollable responsive tables

The big issue with scroll bars and CSS properties such as overflow: auto is that many mobile devices and tablets simply won’t display a visible scroll bar. The right area of the table will be scrollable, but the user will have no visual clue that that’s possible. We have to find some way to indicate that more content lies to the right.

A third approach is to reflow a large table and split up the columns into what essentially looks like list items with headings. This technique is used in the “reflow mode” on jQuery Mobile and was explained by Chris Coyier in his article “Responsive Data Tables.”

Responsive table reflow example
Reflowing a table responsively

Many other techniques exist. Which to use depends heavily on your project. No two projects are the same, so I can only show you how other people have dealt with it. If you come up with a nice solution of your own, please share it with the world in the comments below, on Twitter or elsewhere. We are in this boat together, and tables suck on mobile, really, so let’s improve them together!

Embedding Third-Party Content: The Responsive Iframe Problem

Many websites consist of embedded third-party content: YouTube or Vimeo videos, SlideShare presentations, Facebook applications, Twitter feeds, Google Maps and so on. A lot of those third parties make you use iframes to embed their content. But let’s face it: iframes are a pain to deal with in responsive design. The big problem is that iframes force a fixed width and height directly in your HTML code. Forcing a 100% width on the iframe would work, but then you would lose the ratio of the embedded content. To embed a video or slideshow and preserve the original ratio, you would have to find a workaround.

An HTML and CSS Workaround

Thierry Koblentz has written a good article titled “Creating Intrinsic Ratios for Video,” in which he proposes a way to embed responsive videos using a 16:9 ratio. This solution can be extended to other sorts of iframe content, such as SlideShare presentations and Google Maps. Koblentz wraps the iframe in a container with a class that we can target in CSS. The container makes it possible for the iframe to resize fluidly, even if the iframe has fixed pixel values in the HTML. The code, adapted by Anders M. Andersen, looks like this:


 .embed-container  {
   position: relative;
   padding-bottom: 56.25%; /* 16:9 ratio */
   padding-top: 30px; /* IE 6 workaround*/
   height: 0;
   overflow: hidden;
}

.embed-container iframe,
.embed-container object,
.embed-container embed {
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
}

This will work for all iframes. The only potential problem is that you will have to wrap all of the iframes on your website in a <div class="embed-container"> element. While this would work for developers who have total control over their code or for clients who are reasonably comfortable with HTML, it wouldn’t work for clients who have no technical skill. You could, of course, use some JavaScript to detect iframe elements and automatically embed them in the class. But as you can see, it’s still a major workaround and not a perfect solution.

Dealing With Responsive Video In Future

HTML5 opens a world of possibilities for video — particularly with the video element. The great news is that support for this element is amazingly good for mobile devices! Except for Opera Mini, most major browsers support it. The video element is also pretty flexible. Presenting a responsive video is as simple as this:


video {
   max-width: 100%;
   height: auto;
}

You’re probably asking, “What’s the problem, then?”

The problem is that, even though YouTube or Vimeo may support the video element, you still have to embed videos using the ugly iframe method. And that, my friend, sucks. Until YouTube and Vimeo provide a way to embed videos on websites using the HTML5 video tag, we have to find workarounds to make video embedding work on responsive websites. Chris Coyier created such a workaround as a jQuery plugin called FitVids.js. It uses the first technique mentioned above: creating a wrapper around the iframe to preserve the ratio.

Embedding Google Maps

If you embed a Google Map on your website, the technique described above with the container and CSS will work. But, again, it’s a dirty little hack. Moreover, the map will resize in proportion and might get so tiny that the map loses the focus area that you wanted to show to the user. The Google Maps’ page for mobile says that you can use the static maps API for mobile embedding. Using a static map would indeed make the iframe problems go away. Brad Frost wrote a nice article about, and created a demo of, adaptive maps, which uses this same technique. A JavaScript detects the screen’s size, and then the iframe is replaced by the static map for mobile phones. As you can tell, we again have to resort to a trick to deal with the iframe problem, in the absence of a “native” solution (i.e. from Google).

We Need Better APIs

And now the big question: Is there a better way? The biggest problem with using iframes to embed third-party content responsively is the lack of control over the generated code. Developers and designers are severely dependent on the third party and, by extension, its generated HTML. The number of websites that provide content to other websites is growing quickly. We’ll need much better solutions than iframes to embed this content.

Let’s face it: embedding Facebook’s iframe is a real pain. The lack of control over the CSS can make our work look very sloppy and can even sometimes ruin the design. The Web is a very open place, so perhaps now would be a good time to start thinking about more open APIs! In the future, we will need APIs that are better and simpler to use, so that anyone can embed content flexibly, without relying on unresponsive fixed iframes. Until all of those very big third parties decide to create those APIs, we are stuck with sloppy iframes and will have to resort to tricks to make them workable.

Responsive Navigation: An Overview Of Current Solutions

Another big challenge is what to do with navigation. The more complex and deep the architecture of the website, the more inventive we have to be.

An early attempt to deal with this in a simple way was to convert the navigation into a dropdown menu for small screens. Unfortunately, this was not ideal. First, this solution gets terribly complicated with multiple-level navigation. It can also cause some problems with accessibility. I recommend “Stop Misusing Select Menus” to learn about all of the problems such a technique can create.

Some people, including Brad Frost and Luke Wroblewski, have attempted to solving this problem. Brad Frost compiled some of his techniques on the website This Is Responsive, under the navigation section.

Toggle navigation involves hiding the menu for small devices, displaying only a “menu” link. When the user clicks on it, all of the other links appear as block-level elements below it, pushing the main content below the navigation.

A variant of this, inspired by some native application patterns, is off-canvas navigation. The navigation is hidden beneath a “menu” link or icon. When the user clicks the link, the navigation slides out as a panel from the left or right, pushing the main content over.

Toggle navigation example
Some examples of toggle navigation

The problem with these techniques is that the navigation remains at the top of the screen. In his article “Responsive Navigation: Optimizing for Touch Across Devices,” Luke Wroblewski illustrates which zones are easily accessible for different device types. The top left is the hardest to get to on a mobile device.

Easy touch access for mobile and tablet
Easily accessible screen areas on mobile phones and tablets, according to Luke Wroblewski.

Based on this, Jason Weaver created some demos with navigation at the bottom. One solution is a footer anchor, with navigation put at the bottom of the page for small devices, and a “menu” link that sends users there. It uses the HTML anchor link system.

Many other attempts have been made to solve the navigation problem in responsive Web design. As you can see, there is not yet a perfect solution; it really depends on the project and the depth of the navigation. Fortunately for us, some of the people who have tried to crack this nut have shared their experiences with the community.

Another unsolved issue is what icon to use to tell the user, “Hey! There’s a menu hidden under me. Click me!” Some websites have a plus symbol (+), some have a grid of squares, other have what looks like an unordered list, and some have three lines (aka the burger icon).

Some responsive icons example
To see these icons used on real websites, have a look at “We Need a Standard ‘Show Navigation’ Icon for Responsive Web Design.”

The main problem is figuring out which of these icons would be the most recognizable to the average user. If we all agreed to use one of them, users would be trained to recognize it. The problem is which to choose? I really would like to know which icon you use, so don’t hesitate to share it in the comments below.

Mobile Specificities: “Is The User On A Mobile Device? If So, What Can It Do?”

Mobile and tablet devices are a whole new world, far removed from desktop computers, with their own rules, behaviors and capabilities. We might want to adapt our designs to this new range of capabilities.

Detecting Touch Capabilities With Native JavaScript

Apart from screen size, I bet if you asked what is the main difference between desktop and mobile (including tablets), most people would say touch capability. There is no mouse on a mobile phone (no kidding!), and except for some rare hybrid devices into which you can plug a mouse, you can’t do much with mouse events on a tablet. This means that, depending on the browser, the :hover CSS pseudo-class might not work. Some browsers are clever enough to provide a native fallback for the hover event by translating it into a touch event. Unfortunately, not all browsers are so flexible. Creating a design that doesn’t depend on hidden elements being revealed on :hover events would be wise.

Catching touch events could also be another solution. A W3C working group has started working on a touch event specification. In the future, we will be able to catch events such as touchstart, touchmove and toucheend. We will be able to deal with these events directly in JavaScript without requiring a third-party framework such as Hammer.js or jGestures. But JavaScript is one thing — what about CSS?

CSS Level 4 “Pointer” Media Query

CSS Level 4 specifies a new media query called “pointer”, which can be used to query the presence and accuracy of a pointing device, such as a mouse. The media query takes one of three values:

  • none
    The device does not have any pointing device at all.
  • coarse
    The device has a pointing device with limited accuracy; for example, a mobile phone or tablet with touch capabilities, where the “pointer” would be a finger.
  • fine
    The device has an accurate pointing device, such as a mouse, trackpad or stylus.

Using this media query, we can enlarge buttons and links for touch devices:


@media  (pointer:coarse) {
   input[type="submit"],
       a.button {
       min-width: 30px;
       min-height: 40px;
       background: transparent;
   }
 }

The pointer media query is not yet supported and is merely being proposed. Nevertheless, the potential is huge because it would enable us to detect touch devices via CSS, without the need for a third-party library, such as Modernizr.

CSS Level 4 “Hover” Media Query

The CSS Level 4 specification proposes a new hover media query, which detects whether a device’s primary pointing system can hover. It returns a Boolean: 1 if the device supports hover, 0 if not. Note that it has nothing to do with the :hover pseudo-class.

Using the hover media query, we can enhance an interface to hide certain features for devices that do support hovering. The code would look something like this:


 @media  (hover) {
   .hovercontent { display: none; } /* Hide content only for devices with hover capabilities. */

   .hovercontent:hover { display: block; }    
 }

It can also be used to create dropdown menus on hover; and the fallback for mobile devices is in native CSS, without the need for a feature-detection framework.

CSS Level 4 Luminosity Media Query

Another capability of mobile devices is the luminosity sensor. The CSS Level 4 specification has a media query for luminosity, which gives us access to a device’s light sensors directly in the CSS. Here is how the specification describes it:

“The “luminosity” media feature is used to query about the ambient luminosity in which the device is used, to allow the author to adjust style of the document in response.”

In the future, we will be able to create websites that respond to ambient luminosity. This will greatly improve user experiences. We will be able to detect, for example, exceptionally bright environments using the washed value, adapting the website’s contrast accordingly. The dim value is used for dim environments, such as at nighttime. The normal value is used when the luminosity level does not need any adjustment.

The code would look something like this:


 @media  (luminosity: washed) {
   p { background: white; color: black; font-size: 2em; }
 }

As you can see, CSS Level 4 promises a lot of fun new stuff. If you are curious to see what’s in store, not only mobile-related, then have a look at “Sneak Peek Into the Future: Selectors, Level 4.”

More Mobile Capabilities to Detect Using APIs and JavaScript

Many other things could be detected to make the user experience amazing on a responsive website. For example, we could gain access to the native gyroscope, compass and accelerometer to detect the device’s orientation using the HTML5 DeviceOrientationEvent. Support for DeviceOrientationEvent in Android and iOS browsers is getting better, but the specification is still a draft. Nevertheless, the API look promising. Imagine playing full HTML5 games directly in the browser.

Another API that would be particularly useful for some mobile users is geolocation. The good news is that it’s already well supported. This API enables us to geolocate the user using GPS and to infer their location from network signals such as IP address, RFID, Wi-Fi and Bluetooth MAC addresses. This can be used on some responsive websites to provide users with contextual information. A big restaurant chain could enhance its mobile experience by showing the user the locations of restaurants in their area. The possibilities are endless.

The W3C also proposed a draft for a vibration API. With it, the browser can provide tactile feedback to the user in the form of vibration. This, however, is creeping into the more specific field of Web applications and mobile games in the browser.

Another API that has been highly discussed is the network information API. The possibility of measuring a user’s bandwidth and optimizing accordingly has seduced many developers. We would be able to serve high-quality images to users with high bandwidth and low-quality images to users with low bandwidth. With the bandwidth attribute of the network API, it would be possible to estimate the downloading bandwidth of a user in megabytes per second. The second attribute, metered, is a Boolean that tells us whether the user has a metered connection (such as from a prepaid card). These two attributes are currently accessible only via JavaScript.

Unfortunately, measuring a user’s connection is technically difficult, and a connection could change abruptly. A user could go into a tunnel and lose their connection, or their speed could suddenly drop. So, a magical media query that measures bandwidth looks hypothetical at the moment. Yoav Weiss has written a good article about the problems that such a media query would create and about bandwidth measurement, “Bandwidth Media Queries? We Don’t Need ’Em!

Many other APIs deal with mobile capabilities. If you are interested in learning more, Mozilla has a very detailed list. Most are not yet fully available or standardized, and most are intended more for Web applications than for responsive websites. Nevertheless, it’s a great overview of how large and complex mobile websites could get in future.

Rethinking The Way We And The User Deal With Content

From a technical perspective, there are still a lot of challenges in dealing with content at a global scale. The mobile-first method has been part of the development and design process for a little while now. We could, for example, serve to mobile devices the minimum data that is necessary, and then use JavaScript and AJAX to conditionally load more content and images for desktops and tablets. But to do this, we would also have to rethink how we deal with content and be able to prioritize in order to generate content that is flexible enough and adaptive. A good example of this is the responsive map solution described above: we load an image for mobile, and enhance the experience with a real map for desktops. The more responsive the website, the more complex dealing with content gets. Flexible code can help us to format adaptive content.

One way suggested by some people in the industry is to create responsive sentences by marking up sentences with a lot of spans that have classes, and then displaying certain ones according to screen size. Trimming parts of sentences for small devices is possible with media queries. You can see this technique in action on 37signals’ Signal vs. Noise blog and in Frankie Roberto’s article “Responsive Text.” Even if such technique could be used to enhance small parts of a website, such as the footer slogan, applying it to all of the text on a website is hard to imagine.

This raises an issue in responsive Web design that will become more and more important in future: the importance of meta data and the semantic structure of content. As mentioned, the content on our websites does not only come from in-house writers. If we want to be able to automatically reuse content from other websites, then it has to be well structured and prepared for it. New HTML5 tags such as article and section are a good start to gaining some semantic meaning. The point is to think about and structure content so that a single item (say, a blog post) can be reused and displayed on different devices in different formats.

The big challenge will be to make meta data easily understandable to all of the people who are part of the content creation chain of the website. We’ll have to explain to them how the meta data can be used to prioritize content and be used to programmatically assemble content, while being platform-independent. A huge challenge will be to help them start thinking in terms of reusable blocks, rather than a big chunk of text that they copy and paste from Microsoft Word to their WYSIWYG content management system. We will have to help them understand that content and structure are two separate and independent things, just as when designers had to understand that content (HTML) and presentation (CSS) are best kept separate.

We can’t afford to write content that is oriented towards one only platform anymore. Who knows on which devices our content will be published in six months, or one year? We need to prepare our websites for the unexpected. But to do so, we need better publishing tools, too. Karen McGrane gave a talk on “Adapting Ourselves to Adaptive Content,” with some real example from the publishing industry. She speaks about the process of creating reusable content and introduces the idea of COPE: create once and publish everywhere. We need to build better CMSes, ones that can use and generate meta data to prioritize content. We need to explain to people how the system works and to think in terms of modular reusable content objects, instead of WYSIWYG pages. As McGrane says:

“You might be writing three different versions of that headline; you might be writing two different short summaries and you are attaching a couple of different images to it, different cut sizes, and then you may not be the person who is in charge of deciding what image or what headline gets displayed on that particular platform. That decision will be made by the metadata. It will be made by the business rules. […] Metadata is the new art direction.”

Truncating content for small devices is not a future-proof content strategy. We need CMSes that provide the structure needed to create such reusable content. We need better publishing workflows in CMSes, too. Clunky interfaces scare users, and most people who create content are not particularly comfortable with complicated tools. We will have to provide them with tools that are easy to understand and that help them publish clean, semantic content that is independent of presentation.

Conclusion

As long as this article is, it only scratches the surface. By now, most of Smashing Magazine’s readers understand that responsive Web design is much more than about throwing a bunch of media queries on the page, choosing the right breakpoints and doubling the size of images for those cool new high-density phones. As you can see, the path is long, and we are not there yet. There are still many unsolved issues, and the perfect responsive solution does not exist yet.

Some technical solutions might be discovered in future using some of the new technologies presented here and with the help of the W3C, the WHATWG and organizations such as the Filament Group.

More importantly, we Web designers and developers can help to find even better solutions. People such as Luke Wroblewski and Brad Frost and all of the amazing women and men mentioned in this article are experimenting with a lot of different techniques and solutions. Whether any succeeds or fails, the most important thing is to share what we — as designers, developers, content strategists and members of the Web design community — are doing to try to solve some of the challenges of responsive Web design. After all, we are all in the same boat, trying to make the Web a better place, aren’t we?

(al) (ea)

© Stéphanie Walter for Smashing Magazine, 2013.

0
Your rating: None
Original author: 
Thomas Joos

  

As a mobile UI or UX designer, you probably remember the launch of Apple’s first iPhone as if it was yesterday. Among other things, it introduced a completely touchscreen-centered interaction to a individual’s most private and personal device. It was a game-changer.

Today, kids grow up with touchscreen experiences like it’s the most natural thing. Parents are amazed by how fast their children understand how a tablet or smartphone works. This shows that touch and gesture interactions have a lot of potential to make mobile experiences easier and more fun to use.

Challenging Bars And Buttons

The introduction of “Human Interface Guidelines” and Apple’s App Review Board had a great impact on the quality of mobile applications. It helped a lot of designers and developers understand the core mobile UI elements and interactions. One of Apple’s popular suggestions, for instance, is to use UITabBar and UINavigationBar components — a guideline that many of us have followed, including me.

In fact, if you can honestly say that the first iPhone application you designed didn’t have any top or bottom bar elements, get in touch and send over a screenshot. I will buy you a beer and gladly tweet that you were ahead of your time.

My issue with the top and bottom bars is that they fill almost 20% of the screen. When designing for a tiny canvas, we should use every available pixel to focus on the content. In the end, that’s what really matters.

In this innovative industry, mobile designers need some time to explore how to design more creative and original interfaces. Add to that Apple’s frustrating rejection of apps that “think outside the box,” it is no surprise that experimental UI and UX designs such as Clear and Rise took a while to see the light of day. But they are here now. And while they might be quite extreme and focused on high-brow users and early adopters, they show us the great creative potential of gesture-driven interfaces.

Rise and Clear
Pulling to refresh feels very intuitive.

The Power Of Gesture-Driven Interfaces

For over two years now, I’ve been exploring the ways in which gestures add value to the user experience of a mobile application. The most important criterion for me is that these interactions feel very intuitive. This is why creative interactions such as Loren Brichter’s “Pull to Refresh” have become a standard in no time. Brichter’s interaction, introduced in Tweetie for iPhone, feels so intuitive that countless list-based applications suddenly adopted the gesture upon its appearance.

Removing UI Clutter

A great way to start designing a more gesture-driven interface is to use your main screen only as a viewport to the main content. Don’t feel obliged to make important navigation always visible on the main screen. Rather, consider giving it a place of its own. Speaking in terms of a virtual 2-D or 3-D environment, you could design the navigation somewhere next to, below, behind, in front of, above or hidden on top of the main view. A dragging or swiping gesture is a great way to lead the user to this UI element. It’s up to you to define and design the app.

What I like about Facebook and Gmail on iOS, for instance, is their implementation of a “side-swiping” menu. This trending UI concept is very easy to use. Users swipe the viewport to the right to reveal navigation elements. Not only does this make the app very content-focused, but accessing any section of the application takes only two to three touch interactions. A lot of apps do far worse than that!

Sideswipe Menu
Facebook and Gmail’s side-swiping menu

In addition to the UI navigation, your app probably also supports contextual interactions, too. Adding the same two or three buttons below every content item will certainly clutter the UI! While buttons might seem to be useful triggers, gestures have great potential to make interaction with content more intuitive and fun. Don’t hesitate to integrate simple gestures such as tapping, double-tapping and tapping-and-holding to trigger important interactions. Instagram supports a simple double-tap to perform one of its key features, liking and unliking a content item. I would not be surprised to see other apps integrate this shortcut in the near future.

An Interface That Fits

When designing an innovative mobile product, predicting user behavior can be very difficult. When we worked with Belgium’s Public Radio, my team really struggled with the UI balance between music visualization and real-time news. The sheer number of contextual scenarios and preferences made it very hard to come up with the perfect UI. So, we decided to integrate a simple dragging gesture to enable users to adjust the balance themselves.

Radio+
By dragging, users can balance music-related content and live news.

This gesture adds a creative contextual dimension to the application. The dragging gesture does not take the user from one section (news or music) to another. Rather, it enables the user to focus on the type of content they are most interested in, without missing out on the other.

Think in Terms of Time, Dimension and Animation

What action is triggered when the user taps an item? And how do you visualize that it has actually happened? How fast does a particular UI element animate into the viewport? Does it automatically go off-screen after five seconds of no interaction?

The rise of touch and gesture-driven devices dramatically changes the way we design interaction. Instead of thinking in terms of screens and pages, we are thinking more in terms of time, dimension and animation. You’ve probably noticed that fine-tuning user interactions and demonstrating them to colleagues and clients with static wireframe screenshots is not easy. You don’t fully see, understand and feel what will happen when you touch, hold, drag and swipe items.

Certain prototyping tools, including Pop and Invision, can help bring wireframes to life. They are very useful for testing an application’s flow and for pinpointing where and when a user might get stuck. Your application has a lot more going on than simple back-and-forth navigation, so you need to detect interface bugs and potential sources of confusion as soon as possible. You wouldn’t want your development team to point them out to you now, would you?

InvisionApp
Invision enables you to import and link your digital wireframes.

To be more innovative and experimental, get together with your client first and explain that a traditional wireframe is not the UX deliverable that they need. Show the value of interactive wireframes and encourage them to include this in the process. It might increase the timeline and budget, but if they are expecting you to go the extra mile, it shouldn’t be a problem.

I even offer to produce a conceptual interface video for my clients as well, because once they’ve worked with the interactive wireframes and sorted out the details, my clients will often need something sexier to present to their internal stakeholders.

The Learning Curve

When designing gesture-based interactions, be aware that every time you remove UI clutter, the application’s learning curve goes up. Without visual cues, users could get confused about how to interact with the application. A bit of exploration is no problem, but users should know where to begin. Many apps show a UI walkthrough when first launched, and I agree with Max Rudberg that walkthroughs should explain only the most important interactions. Don’t explain everything at once. If it’s too explicit and long, users will skip it.

Why not challenge yourself and gradually introduce creative UI hints as the user uses the application? This pattern is often referred to as progressive disclosure and is a great way to show only the information that is relevant to the user’s current activity. YouTube’s Capture application, for instance, tells the user to rotate the device to landscape orientation just as the user is about to open the camera for the first time.

Visual Hints
Fight the learning curve with a UI walkthrough and/or visual hints.

Adding visual cues to the UI is not the only option. In the Sparrow app, the search bar appears for a few seconds, before animating upwards and going off screen, a subtle way to say that it’s waiting to be pulled down.

Stop Talking, Start Making

The iPhone ushered in a revolution in interactive communication. Only five years later, touchscreen devices are all around us, and interaction designers are redefining the ways people use digital content.

We need to explore and understand the potential of touch and gesture-based interfaces and start thinking more in terms of time, dimension and animation. As demonstrated by several innovative applications, gestures are a great way to make an app more content-focused, original and fun. And many gesture-based interactions that seem too experimental at first come to be seen as very intuitive.

For a complete overview of the opportunities for gestures on all major mobile platforms, check out Luke Wroblewski’s “Touch Gesture Reference Overview.” I hope you’re inspired to explore gesture-based interaction and intensify your adventures in mobile interfaces. Don’t be afraid to go the extra mile. With interactive wireframes, you can iterate your way to the best possible experience. So, let’s stop talking and start making.

(al)

© Thomas Joos for Smashing Magazine, 2013.

0
Your rating: None
Original author: 
Wilson Page

  

When the mockups for the new Financial Times application hit our desks in mid-2012, we knew we had a real challenge on our hands. Many of us on the team (including me) swore that parts of interface would not be possible in HTML5. Given the product team’s passion for the new UI, we rolled up our sleeves and gave it our best shot.

We were tasked with implementing a far more challenging product, without compromising the reliable, performant experience that made the first app so successful.

promo-500-compr

We didn’t just want to build a product that fulfilled its current requirements; we wanted to build a foundation that we could innovate on in the future. This meant building with a maintenance-first mentality, writing clean, well-commented code and, at the same time, ensuring that our code could accommodate the demands of an ever-changing feature set.

In this article, I’ll discuss some of the changes we made in the latest release and the decision-making behind them. I hope you will come away with some ideas and learn from our solutions as well as our mistakes.

Supported Devices

The first Financial Times Web app ran on iPad and iPhone in the browser, and it shipped in a native (PhoneGap-esque) application wrapper for Android and Windows 8 Metro devices. The latest Web app is currently being served to iPad devices only; but as support is built in and tested, it will be rolled out to all existing supported platforms. HTML5 gives developers the advantage of occupying almost any mobile platform. With 2013 promising the launch of several new Web application marketplaces (eg. Chrome Web Store and Mozilla Marketplace), we are excited by the possibilities that lie ahead for the mobile Web.

Fixed-Height Layouts

The first shock that came from the new mockups was that they were all fixed height. By “fixed height,” I mean that, unlike a conventional website, the height of the page is restricted to the height of the device’s viewport. If there is more content than there is screen space, overflow must be dealt with at a component level, as opposed to the page level. We wanted to use JavaScript only as a last resort, so the first tool that sprang to mind was flexbox. Flexbox gives developers the ability to declare flexible elements that can fill the available horizontal or vertical space, something that has been very tricky to do with CSS. Chris Coyier has a great introduction to flexbox.

Using Flexbox in Production

Flexbox has been around since 2009 and has great support on all the popular smartphones and tablets. We jumped at the chance to use flexbox when we found out how easily it could solve some of our complex layouts, and we started throwing it at every layout problem we faced. As the app began to grow, we found performance was getting worse and worse.

We spent a good few hours in Chrome Developers Tools’ timeline and found the culprit: Shock, horror! — it was our new best friend, flexbox. The timeline showed that some layouts were taking close to 100 milliseconds; reworking our layouts without flexbox reduced this to 10 milliseconds! This may not seem like a lot, but when swiping between sections, 90 milliseconds of unresponsiveness is very noticeable.

Back to the Old School

We had no other choice but to tear out flexbox wherever we could. We used 100% height, floats, negative margins, border-box sizing and padding to achieve the same layouts with much greater performance (albeit with more complex CSS). Flexbox is still used in some parts of the app. We found that its impact on performance was less expensive when used for small UI components.

layout-time-with-flexbox-500_comp
Page layout time with flexbox

layout-time-without-flexbox-500_comp
Page layout time without flexbox

Truncation

The content of a fixed-height layout will rarely fit its container; eventually it has to overflow. Traditionally in print, designers have used ellipses (three dots) to solve this problem; however, on the Web, this isn’t the simplest technique to implement.

Ellipsis

You might be familiar with the text-overflow: ellipsis declaration in CSS. It works great, has awesome browser support, but has one shortfall: it can’t be used for text that spans multiple lines. We needed a solution that would insert an ellipsis at the point where the paragraph overflows its container. JavaScript had to step in.

ellipsis-500_mini
Ellipsis truncation is used throughout.

After an in-depth research and exploration of several different approaches, we created our FTEllipsis library. In essence, it measures the available height of the container, then measures the height of each child element. When it finds the child element that overflows the container, it caps its height to a sensible number of lines. For WebKit-based browsers, we use the little-known -webkit-line-clamp property to truncate an element’s text by a set number of lines. For non-WebKit browsers, the library allows the developer to style the overflowing container however they wish using regular CSS.

Modularization

Having tackled some of the low-level visual challenges, we needed to step back and decide on the best way to manage our application’s views. We wanted to be able to reuse small parts of our views in different contexts and find a way to architect rock-solid styling that wouldn’t leak between components.

One of the best decisions we made in implementing the new application was to modularize the views. This started when we were first looking over the designs. We scribbled over printouts, breaking the page down into chunks (or modules). Our plan was to identify all of the possible layouts and modules, and define each view (or page) as a combination of modules sitting inside the slots of a single layout.

Each module needed to be named, but we found it very hard to describe a module, especially when some modules could have multiple appearances depending on screen size or context. As a result, we abandoned semantic naming and decided to name each component after a type of fruit — no more time wasted thinking up sensible, unambiguous names!

An example of a module’s markup:


<div class="apple">
  <h2 class="apple_headline">{{headline}}</h2>
  <h3 class="apple_sub-head">{{subhead}}</h3>
  <div class="apple_body">{{body}}</div>
</div>

An example of a module’s styling:


.apple {}

.apple_headline {
  font-size: 40px;
}

.apple_sub-head {
  font-size: 20px;
}

.apple_body {
  font-size: 14px;
  column-count: 2;
  color: #333;
}

Notice how each class is prefixed with the module’s name. This ensures that the styling for one component will never affect another; every module’s styling is encapsulated. Also, notice how we use just one class in our CSS selectors; this makes our component transportable. Ridding selectors of any ancestral context means that modules may be dropped anywhere in our application and will look the same. This is all imperative if we want to be able to reuse components throughout the application (and even across applications).

What If a Module Needs Interactions?

Each module (or fruit) has its own markup and style, which we wrote in such a way that it can be reused. But what if we need a module to respond to interactions or events? We need a way to bring the component to life, but still ensure that it is unbound from context so that it can be reused in different places. This is a little trickier that just writing smart markup and styling. To solve this problem, we wrote FruitMachine.

Reusable Components

FruitMachine is a lightweight library that assembles our layout’s components and enables us to declare interactions on a per-module basis. It was inspired by the simplicity of Backbone views, but with a little more structure to keep “boilerplate” code to a minimum. FruitMachine gives our team a consistent way to work with views, while at the same time remaining relatively unopinionated so that it can be used in almost any view.

The Component Mentality

Thinking about your application as a collection of standalone components changes the way you approach problems. Components need to be dumb; they can’t know anything of their context or of the consequences of any interactions that may occur within them. They can have a public API and should emit events when they are interacted with. An application-specific controller assembles each layout and is the brain behind everything. Its job is to create, control and listen to each component in the view.

For example, to show a popover when a component named “button” is clicked, we would not hardcode this logic into the button component. Instead “button” would emit a buttonclicked event on itself every time its button is clicked; the view controller would listen for this event and then show the popover. By working like this, we can create a large collection of components that can be reused in many different contexts. A view component may not have any application-specific dependencies if it is to be used across projects.

Working like this has simplified our architecture considerably. Breaking down our views into components and decoupling them from our application focuses our decision-making and moves us away from baking complex, heavily dependent modules into our application.

The Future of FruitMachine

FruitMachine was our solution to achieve fully transportable view components. It enables us to quickly define and assemble views with minimal effort. We are currently using FruitMachine only on the client, but server-side (NodeJS) usage has been considered throughout development. In the coming months, we hope to move towards producing server-side-rendered websites that progressively enhance into a rich app experience.

You can find out more about FruitMachine and check out some more examples in the public GitHub repository.

Retina Support

The Financial Times’ first Web app was released before the age of “Retina” screens. We retrofitted some high-resolution solutions, but never went the whole hog. For our designers, 100% Retina support was a must-have in the new application. We developers were sick of maintaining multiple sizes and resolutions of each tiny image within the UI, so a single vector-based solution seemed like the best approach. We ended up choosing icon fonts to replace our old PNGs, and because they are implemented just like any other custom font, they are really well supported. SVG graphics were considered, but after finding a lack of support in Android 2.3 and below, this option was ruled out. Plus, there is something nice about having all of your icons bundled up in a single file, whilst not sacrificing the individuality of each graphic (like sprites).

Our first move was to replace the Financial Times’ logo image with a single glyph in our own custom icon font. A font glyph may be any color and size, and it always looks super-sharp and is usually lighter in weight than the original image. Once we had proved it could work, we began replacing every UI image and icon with an icon font alternative. Now, the only pixel-based image in our CSS is the full-color logo on the splash screen. We used the powerful but rather archaic-looking FontForge to achieve this.

Once past the installation phase, you can open any font file in FontForge and individually change the vector shape of any character. We imported SVG vector shapes (created in Adobe Illustrator) into suitable character slots of our font and exported as WOFF and TTF font types. A combination of WOFF and TTF file formats are required to support iOS, Android and Windows devices, although we hope to rely only on WOFFs once Android gains support (plus, WOFFs are around 25% smaller in file size than TTFs).

icon-font-500-compr
The Financial Times’ icon font in Font Forge

Images

Article images are crucial for user engagement. Our images are delivered as double-resolution JPEGs so that they look sharp on Retina screens. Our image service (running ImageMagick) outputs JPEGs at the lowest possible quality level without causing noticeable degradation (we use 35 for Retina devices and 70 for non-Retina). Scaling down retina size images in the browser enables us to reduce JPEG quality to a lower level than would otherwise be possible without compression artifacts becoming noticeable. This article explains this technique in more detail.

It’s worth noting that this technique does require the browser to work a little harder. In old browsers, the work of scaling down many large images could have a noticeable impact on performance, but we haven’t encountered any serious problems.

Native-Like Scrolling

Like almost any application, we require full-page and subcomponent scrolling in order to manage all of the content we want to show our users. On desktop, we can make use of the well-established overflow CSS property. When dealing with the mobile Web, this isn’t so straightforward. We require a single solution that provides a “momentum” scrolling experience across all of the devices we support.

overflow: scroll

The overflow: scroll declaration is becoming usable on the mobile Web. Android and iOS now support it, but only since Android 3.0 and iOS 5. IOS 5 came with the exciting new -webkit-overflow-scrolling: touch property, which allows for native momentum-like scrolling in the browser. Both of these options have their limitations.

Standard overflow: scroll and overflow: auto don’t display scroll bars as users might expect, and they don’t have the momentum touch-scrolling feel that users have become accustomed to from their native apps. The -webkit-overflow-scrolling: touch declaration does add momentum scrolling and scroll bars, but it doesn’t allow developers to style the scroll bars in any way, and has limited support (iOS 5+ and Chrome on Android).

A Consistent Experience

Fragmented support and an inconsistent feel forced us to turn to JavaScript. Our first implementation used the TouchScroll library. This solution met our needs, but as our list of supported devices grew and as more complex scrolling interactions were required, working with it became trickier. TouchScroll lacks IE 10 support, and its API interface is difficult to work with. We also tried Scrollability and Zynga Scroller, neither of which have the features, performance or cross-browser capability we were looking for. Out of this problem, FTScroller was developed: a high-performance, momentum-scrolling library with support for iOS, Android, Playbook and IE 10.

FTScroller

FTScroller’s scrolling implementation is similar to TouchScroll’s, with a flexible API much like Zynga Scroller. We added some enhancements, such as CSS bezier curves for bouncing, requestAnimationFrame for smoother frame rates, and support for IE 10. The advantage of writing our own solution is that we could develop a product that exactly meets our requirements. When you know the code base inside out, fixing bugs and adding features is a lot simpler.

FTScroller is dead simple to use. Just pass in the element that will wrap the overflowing content, and FTScroller will implement horizontal or vertical scrolling as and when needed. Many other options may be declared in an object as the second argument, for more custom requirements. We use FTScroller throughout the Financial Times’ Web app for a consistent cross-platform scrolling experience.

A simple example:


var container = document.getElementById('scrollcontainer');
var scroller = new FTScroller(container);

The Gallery

The part of our application that holds and animates the page views is known as the “gallery.” It consists of three divisions: left, center and right. The page that is currently in view is located in the center pane. The previous page is positioned off screen in the left-hand pane, and the next page is positioned off screen in the right-hand pane. When the user swipes to the next page, we use CSS transitions to animate the three panes to the left, revealing the hidden right pane. When the transition has finished, the right pane becomes the center pane, and the far-left pane skips over to become the right pane. By using only three page containers, we keep the DOM light, while still creating the illusion of infinite pages.

Web
Infinite scrolling made possible with a three-pane gallery

Making It All Work Offline

Not many Web apps currently offer an offline experience, and there’s a good reason for that: implementing it is a bloody pain! The application cache (AppCache) at first glance appears to be the answer to all offline problems, but dig a little deeper and stuff gets nasty. Talks by Andrew Betts and Jake Archibald explain really well the problems you will encounter. Unfortunately, AppCache is currently the only way to achieve offline support, so we have to work around its many deficiencies.

Our approach to offline is to store as little in the AppCache as possible. We use it for fonts, the favicon and one or two UI images — things that we know will rarely or never need updating. Our JavaScript, CSS and templates live in LocalStorage. This approach gives us complete control over serving and updating the most crucial parts of our application. When the application starts, the bare minimum required to get the app up and running is sent down the wire, embedded in a single HTML page; we call this the preload.

We show a splash screen, and behind the scenes we make a request for the application’s full resources. This request returns a big JSON object containing our JavaScript, CSS and Mustache templates. We eval the JavaScript and inject the CSS into the DOM, and then the application launches. This “bootstrap” JSON is then stored in LocalStorage, ready to be used when the app is next started up.

On subsequent startups, we always use the JSON from LocalStorage and then check for resource updates in the background. If an update is found, we download the latest JSON object and replace the existing one in LocalStorage. Then, the next time the app starts, it launches with the new assets. If the app is launched offline, the startup process is the same, except that we cannot make the request for resource updates.

Images

Managing offline images is currently not as easy as it should be. Our image requests are run through a custom image loader and cached in the local database (IndexedDB or WebSQL) so that the images can be loaded when a network connection is not present. We never load images in the conventional way, otherwise they would break when users are offline.

Our image-loading process:

  1. The loader scans the page for image placeholders declared by a particular class.
  2. It takes the src attribute of each image placeholder found and requests the source from our JavaScript image-loader library.
  3. The local database is checked for each image. Failing that, a single HTTP request is made listing all missing images.
  4. A JSON array of Base64-encoded images is returned from the HTTP response and stored separately in the local database.
  5. A callback is fired for each image request, passing the Base64 string as an argument.
  6. An <img> element is created, and its src attribute is set to the Base64 data-URI string.
  7. The image is faded in.

I should also mention that we compress our Base64-encoded image strings in order to fit as many images in the database as possible. My colleague Andrew Betts goes into detail on how this can be achieved.

In some cases, we use this cool trick to handle images that fail to load:


<img src="image.jpg" onerror="this.style.display='none';" />

Ever-Evolving Applications

In order to stay competitive, a digital product needs to evolve, and as developers, we need to be prepared for this. When the request for a redesign landed at the Financial Times, we already had a fast, popular, feature-rich application, but it wasn’t built for change. At the time, we were able to implement small changes to features, but implementing anything big became a slow process and often introduced a lot of unrelated regressions.

Our application was drastically reworked to make the new requirements possible, and this took a lot of time. Having made this investment, we hope the new application not only meets (and even exceeds) the standard of the first product, but gives us a platform on which we can develop faster and more flexibly in the future.

(al)

© Wilson Page for Smashing Magazine, 2013.

0
Your rating: None
Original author: 
David Storey

  

Flexible box layout (or flexbox) is a new box model optimized for UI layout. As one of the first CSS modules designed for actual layout (floats were really meant mostly for things such as wrapping text around images), it makes a lot of tasks much easier, or even possible at all. Flexbox’s repertoire includes the simple centering of elements (both horizontally and vertically), the expansion and contraction of elements to fill available space, and source-code independent layout, among others abilities.

Flexbox has lived a storied existence. It started as a feature of Mozilla’s XUL, where it was used to lay out application UI, such as the toolbars in Firefox, and it has since been rewritten multiple times. The specification has only recently reached stability, and we have fairly complete support across the latest versions of the leading browsers.

There are, however, some caveats. The specification changed between the implementation in Internet Explorer (IE) and the release of IE 10, so you will need to use a slightly different syntax. Chrome currently still requires the -webkit- prefix, and Firefox and Safari are still on the much older syntax. Firefox has updated to the latest specification, but that implementation is currently behind a runtime flag until it is considered stable and bug-free enough to be turned on by default. Until then, Firefox still requires the old syntax.

When you specify that an element will use the flexbox model, its children are laid out along either the horizontal or vertical axis, depending on the direction specified. The widths of these children expand or contract to fill the available space, based on the flexible length they are assigned.

Example: Horizontal And Vertical Centering (Or The Holy Grail Of Web Design)

Being able to center an element on the page is perhaps the number one wish among Web designers — yes, probably even higher than gaining the highly prized parent selector or putting IE 6 out of its misery (OK, maybe a close second then). With flexbox, this is trivially easy. Let’s start with a basic HTML template, with a heading that we want to center. Eventually, once we’ve added all the styling, it will end up looking like this vertically and horizontally centered demo.


<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="utf-8"/>
   <title>Centering an Element on the Page</title>
</head>
<body>
   <h1>OMG, I’m centered</h1>
</body>
</html>

Nothing special here, not even a wrapper div. The magic all happens in the CSS:


html {
   height: 100%;
} 

body {
   display: -webkit-box;   /* OLD: Safari,  iOS, Android browser, older WebKit browsers.  */
   display: -moz-box;   /* OLD: Firefox (buggy) */ 
   display: -ms-flexbox;   /* MID: IE 10 */
   display: -webkit-flex;    /* NEW, Chrome 21+ */
   display: flex;       /* NEW: Opera 12.1, Firefox 22+ */

   -webkit-box-align: center; -moz-box-align: center; /* OLD… */
   -ms-flex-align: center; /* You know the drill now… */
   -webkit-align-items: center;
   align-items: center;

    -webkit-box-pack: center; -moz-box-pack: center; 
   -ms-flex-pack: center; 
   -webkit-justify-content: center;
   justify-content: center;

   margin: 0;
   height: 100%;
   width: 100% /* needed for Firefox */
} 

h1 {
   display: -webkit-box; display: -moz-box;
   display: -ms-flexbox;
   display: -webkit-flex;
   display: flex;
 
   -webkit-box-align: center; -moz-box-align: center;
   -ms-flex-align: center;
   -webkit-align-items: center;
   align-items: center;

   height: 10rem;
}

I’ve included all of the different prefixed versions in the CSS above, from the very oldest, which is still needed, to the modern and hopefully final syntax. This might look confusing, but the different syntaxes map fairly well to each other, and I’ve included tables at the end of this article to show the exact mappings.

This is not exactly all of the CSS needed for our example, because I’ve stripped out the extra styling that you probably already know how to use in order to save space.

Let’s look at the CSS that is needed to center the heading on the page. First, we set the html and body elements to have 100% height and remove any margins. This will make the container of our h1 take up the full height of the browser’s window. Firefox also needs a width specified on the body to force it to behave. Now, we just need to center everything.

Enabling Flexbox

Because the body element contains the heading that we want to center, we will set its display value to flex:


body {
   display: flex;
}

This switches the body element to use the flexbox layout, rather than the regular block layout. All of its children in the flow of the document (i.e. not absolutely positioned elements) will now become flex items.

The syntax used by IE 10 is display: -ms-flexbox, while older Firefox and WebKit browsers use display: -prefix-box (where prefix is either moz or webkit). You can see the tables at the end of this article to see the mappings of the various versions.

What do we gain now that our elements have been to yoga class and become all flexible? They gain untold powers: they can flex their size and position relative to the available space; they can be laid out either horizontally or vertically; and they can even achieve source-order independence. (Two holy grails in one specification? We’re doing well.)

Centering Horizontally

Next, we want to horizontally center our h1 element. No big deal, you might say; but it is somewhat easier than playing around with auto margins. We just need to tell the flexbox to center its flex items. By default, flex items are laid out horizontally, so setting the justify-content property will align the items along the main axis:


body {
   display: flex;
   justify-content: center;
}

For IE 10, the property is called flex-pack, while for older browsers it is box-pack (again, with the appropriate prefixes). The other possible values are flex-start, flex-end, space-between and space-around. These are start, end, justify and distribute, respectively, in IE 10 and the old specification (distribute is, however, not supported in the old specification). The flex-start value aligns to the left (or to the right with right-to-left text), flex-end aligns to the right, space-between evenly distributes the elements along the axis, and space-around evenly distributes along the axis, with half-sized spaces at the start and end of the line.

To explicitly set the axis that the element is aligned along, you can do this with the flex-flow property. The default is row, which will give us the same result that we’ve just achieved. To align along the vertical axis, we can use flex-flow: column. If we add this to our example, you will notice that the element is vertically centered but loses the horizontal centering. Reversing the order by appending -reverse to the row or column values is also possible (flex-flow: row-reverse or flex-flow: column-reverse), but that won’t do much in our example because we have only one item.

There are some differences here in the various versions of the specification, which are highlighted at the end of this article. Another caveat to bear in mind is that flex-flow directions are writing-mode sensitive. That is, when using writing-mode: vertical-rl to switch to vertical text layout (as used traditionally in China, Japan and Korea), flex-flow: row will align the items vertically, and column will align them horizontally.

Centering Vertically

Centering vertically is as easy as centering horizontally. We just need to use the appropriate property to align along the “cross-axis.” The what? The cross-axis is basically the axis perpendicular to the main one. So, if flex items are aligned horizontally, then the cross-axis would be vertical, and vice versa. We set this with the align-items property (flex-align in IE 10, and box-align for older browsers):


body {
   /* Remember to use the other versions for IE 10 and older browsers! */
   display: flex;
   justify-content: center;
   align-items: center;
}

This is all there is to centering elements with flexbox! We can also use the flex-start (start) and flex-end (end) values, as well as baseline and stretch. Let’s have another look at the finished example:

figure1.1_mini
Simple horizontal and vertical centering using flexbox. Larger view.

You might notice that the text is also center-aligned vertically inside the h1 element. This could have been done with margins or a line height, but we used flexbox again to show that it works with anonymous boxes (in this case, the line of text inside the h1 element). No matter how high the h1 element gets, the text will always be in the center:


h1 {
   /* Remember to use the other versions for IE 10 and older browsers! */
   display: flex;
   align-items: center;
   height: 10rem;
}

Flexible Sizes

If centering elements was all flexbox could do, it’d be pretty darn cool. But there is more. Let’s see how flex items can expand and contract to fit the available space within a flexbox element. Point your browser to this next example.

figure1.2_mini
An interactive slideshow built using flexbox. Larger view.

The HTML and CSS for this example are similar to the previous one’s. We’re enabling flexbox and centering the elements on the page in the same way. In addition, we want to make the title (inside the header element) remain consistent in size, while the five boxes (the section elements) adjust in size to fill the width of the window. To do this, we use the new flex property:


section {
   /* removed other styles to save space */
   -prefix-box-flex: 1; /* old spec webkit, moz */
   flex: 1;
   height: 250px;
}

What we’ve just done here is to make each section element take up 1 flex unit. Because we haven’t set any explicit width, each of the five boxes will be the same width. The header element will take up a set width (277 pixels) because it is not flexible. We divide the remaining width inside the body element by 5 to calculate the width of each of the section elements. Now, if we resize the browser window, the section elements will grow or shrink.

In this example, we’ve set a consistent height, but this could be set to be flexible, too, in exactly the same way. We probably wouldn’t always want all elements to be the same size, so let’s make one bigger. On hover, we’ve set the element to take up 2 flex units:


section:hover {
   -prefix-box-flex: 2;
   flex: 2;
   cursor: pointer;
}

Now the available space is divided by 6 rather than 5, and the hovered element gets twice the base amount. Note that an element with 2 flex units does not necessarily become twice as wide as one with 1 unit. It just gets twice the share of the available space added to its “preferred width.” In our examples, the “preferred width” is 0 (the default).

Source-Order Independence

For our last party trick, we’ll study how to achieve source-order independence in our layouts. When clicking on a box, we will tell that element to move to the left of all the other boxes, directly after the title. All we have to do is set the order with the order property. By default, all flex items are in the 0 position. Because they’re in the same position, they follow the source order. Click on your favorite person in the updated example to see their order change.

figure1.3_mini
An interactive slideshow with flex-order. Larger view.

To make our chosen element move to the first position, we just have to set a lower number. I chose -1. We also need to set the header to -1 so that the selected section element doesn’t get moved before it:


header {
   -prefix-box-ordinal-group: 1; /* old spec; must be positive */
   -ms-flex-order: -1; /* IE 10 syntax */
   order: -1; /* new syntax */
} 

section[aria-pressed="true"] {
   /* Set order lower than 0 so it moves before other section elements,
      except old spec, where it must be positive.
 */
   -prefix-box-ordinal-group: 1;
   -ms-flex-order: -1;
   order: -1;

   -prefix-box-flex: 3;
   flex: 3;
   max-width: 370px; /* Stops it from getting too wide. */
}

In the old specification, the property for setting the order (box-ordinal-group) accepts only a positive integer. Therefore, I’ve set the order to 2 for each section element (code not shown) and updated it to 1 for the active element. If you are wondering what aria-pressed="true" means in the example above, it is a WAI-ARIA attribute/value that I add via JavaScript when the user clicks on one of the sections.

This relays accessibility hints to the underlying system and to assistive technology to tell the user that that element is pressed and, thus, active. If you’d like more information on WAI-ARIA, check out “Introduction to WAI-ARIA” by Gez Lemon. Because I’m adding the attribute after the user clicks, this example requires a simple JavaScript file in order to work, but flexbox itself doesn’t require it; it’s just there to handle the user interaction.

Hopefully, this has given you some inspiration and enough introductory knowledge of flexbox to enable you to experiment with your own designs.

Syntax Changes

As you will have noticed throughout this article, the syntax has changed a number of times since it was first implemented. To aid backward- and forward-porting between the different versions, we’ve included tables below, which map the changes between the specifications.

Specification versions

Specification
IE
Opera
Firefox
Chrome
Safari

Standard
11?
12.10+ *
Behind flag
21+ (-webkit-)

Mid
10 (-ms-)

Old

3+ (-moz-)
<21 (-webkit-)
3+ (-webkit-)

* Opera will soon switch to WebKit. It will then require the -webkit- prefix if it has not been dropped by that time.

Enabling flexbox: setting an element to be a flex container

Specification
Property name
Block-level flex
Inline-level flex

Standard
display
flex
inline-flex

Mid
display
flexbox
inline-flexbox

Old
display
box
inline-box

Axis alignment: specifying alignment of items along the main flexbox axis

Specification
Property name
start
center
end
justify
distribute

Standard
justify-content
flex-start
center
flex-end
space-between
space-around

Mid
flex-pack
start
center
end
justify
distribute

Old
box-pack
start
center
end
justify
N/A

Cross-axis alignment: specifying alignment of items along the cross-axis

Specification
Property name
start
center
end
baseline
stretch

Standard
align-items
flex-start
center
flex-end
baseline
stretch

Mid
flex-align
start
center
end
baseline
stretch

Old
box-align
start
center
end
baseline
stretch

Individual cross-axis alignment: override to align individual items along the cross-axis

Specification
Property name
auto
start
center
end
baseline
stretch

Standard
align-self
auto
flex-start
center
flex-end
baseline
stretch

Mid
flex-item-align
auto
start
center
end
baseline
stretch

Old
N/A

Flex line alignment: specifying alignment of flex lines along the cross-axis

Specification
Property name
start
center
end
justify
distribute
stretch

Standard
align-content
flex-start
center
flex-end
space-between
space-around
stretch

Mid
flex-line-pack
start
center
end
justify
distribute
stretch

Old
N/A

This takes effect only when there are multiple flex lines, which is the case when flex items are allowed to wrap using the flex-wrap property and there isn’t enough space for all flex items to display on one line. This will align each line, rather than each item.

Display order: specifying the order of flex items

Specification
Property name
Value

Standard
order

Mid
flex-order
<number>

Old
box-ordinal-group
<integer>

Flexibility: specifying how the size of items flex

Specification
Property name
Value

Standard
flex
none | [ <flex-grow> <flex-shrink>? || <flex-basis>]

Mid
flex
none | [ [ <pos-flex> <neg-flex>? ] || <preferred-size> ]

Old
box-flex
<number>

The flex property is more or less unchanged between the new standard and the draft supported by Microsoft. The main difference is that it has been converted to a shorthand in the new version, with separate properties: flex-grow, flex-shrink and flex-basis. The values may be used in the same way in the shorthand. However, the default value for flex-shrink (previously called negative flex) is now 1. This means that items do not shrink by default. Previously, negative free space would be distributed using the flex-shrink ratio, but now it is distributed in proportion to flex-basis multiplied by the flex-shrink ratio.

Direction: specifying the direction of the main flexbox axis

Specification
Property name
Horizontal
Reversed horizontal
Vertical
Reversed vertical

Standard
flex-direction
row
row-reverse
column
column-reverse

Mid
flex-direction
row
row-reverse
column
column-reverse

Old
box-orient

box-direction
horizontal

normal
horizontal

reverse
vertical

normal
vertical

reverse

In the old version of the specification, the box-direction property needs to be set to reverse to get the same behavior as row-reverse or column-reverse in the later version of the specification. This can be omitted if you want the same behavior as row or column because normal is the initial value.

When setting the direction to reverse, the main flexbox axis is flipped. This means that when using a left-to-right writing system, the items will display from right to left when row-reverse is specified. Similarly, column-reverse will lay out flex items from bottom to top, instead of top to bottom.

The old version of the specification also has writing mode-independent values for box-orient. When using a left-to-write writing system, horizontal may be substituted for inline-axis, and vertical may be substituted for block-axis. If you are using a top-to-bottom writing system, such as those traditional in East Asia, then these values would be flipped.

Wrapping: specifying whether and how flex items wrap along the cross-axis

Specification
Property name
No wrapping
Wrapping
Reversed wrap

Standard
flex-wrap
nowrap
wrap
wrap-reverse

Mid
flex-wrap
nowrap
wrap
wrap-reverse

Old
box-lines
single
multiple
N/A

The wrap-reverse value flips the start and end of the cross-axis, so that if flex items are laid out horizontally, instead of items wrapping onto a new line below, they will wrap onto a new line above.

At the time of writing, Firefox does not support the flex-wrap or older box-lines property. It also doesn’t support the shorthand.

The current specification has a flex-flow shorthand, which controls both wrapping and direction. The behavior is the same as the one in the version of the specification implemented by IE 10. It is also currently not supported by Firefox, so I would recommend to avoid using it when specifying only the flex-direction value.

Conclusion

Well, that’s a (flex-)wrap. In this article, I’ve introduced some of the myriad of possibilities afforded by flexbox. Be it source-order independence, flexible sizing or just the humble centering of elements, I’m sure you can find ways to employ flexbox in your websites and applications. The syntax has settled down (finally!), and implementations are here. All major browsers now support flexbox in at least their latest versions.

While some browsers use an older syntax, Firefox looks like it is close to updating, and IE 11 uses the latest version in leaked Windows Blue builds. There is currently no word on Safari, but it is a no-brainer considering that Chrome had the latest syntax before the Blink-WebKit split. For the time being, use the tables above to map the various syntaxes, and get your flex on.

Layout in CSS is only getting more powerful, and flexbox is one of the first steps out of the quagmire we’ve found ourselves in over the years, first with table-based layouts, then float-based layouts. IE 10 already supports an early draft of the Grid layout specification, which is great for page layout, and Regions and Exclusions will revolutionize how we handle content flow and layout.

Flexbox can be used today if you only need to support relatively modern browsers or can provide a fallback, and in the not too distant future, all sorts of options will be available, so that we can use the best tool for the job. Flexbox is shaping up to be a mighty fine tool.

Further Reading

(al)

© David Storey for Smashing Magazine, 2013.

0
Your rating: None

  

Many of us care deeply about developing our craft. But staying up to date can be a true challenge, because the quantity of fresh information we’re regularly exposed to can be a lot to take in. 2012 has been no exception, with a wealth of evolution and refinement going on in the front end.

Great strides have been made in how we approach workflow, use abstractions, appreciate code quality and tackle the measurement and betterment of performance. If you’ve been busy and haven’t had time to catch up on the latest developments in these areas, don’t worry.

With the holiday season upon us and a little more time on our hands, I thought it would be useful to share a carefully curated list of the most relevant front-end talks I’ve found helpful this year. You certainly don’t have to read through them all, but the advice shared in them will equip you with the knowledge needed to go into the new year as a better front-end engineer.

Screenshot
Image credit: Jacob Bøtter

Baseline

Have a Strategy for Staying Up to Date

How to Stay Up to Date on Web Stuff, Chris Coyier

Part of continually developing your craft is staying up to date. Doing this is important for all professionals, and in this talk you’ll learn strategies for staying updated even when the ideas that surround the technologies we use are constantly evolving.

Screenshot

Make Sure Your Baseline for Development Is Current

A New Baseline for Front-End Developers, Rebecca Murphey

There was a time when editing files, testing them locally and simply FTP’ing them was the common workflow for a front-end developer. We would measure our abilities based on how well we could harass IE 6 into rendering pages correctly, and we generally lacked strong skills in HTML, CSS and JavaScript.

This has greatly changed over the past few years, with improvements in workflow and tooling. Front-end development is now taken more seriously, and this talk sheds light on the new baseline process for developing on the front end.

Screenshot

Understand How Browsers Work Behind the Scenes

So, You Want to Be a Front-End Engineer, David Mosher (Video)

Some would say that the browser is the most volatile development platform the world has ever known. If you’re a client-side developer, understanding how browser internals work can help you both make better decisions and appreciate the justifications behind many development best practices. In one of the best talks this year, David Mosher takes you through how browsers parse and render your pages.

Screenshot

Know What the Web Platform Now Has to Offer

The Web Can Do That!?, Eric Bidelman (Video)

The Web is constantly evolving, and keeping up with what’s new on the platform can be hard. HTML5’s new capabilities enable us to build an entirely new suite of applications with features that were simply impossible to achieve before (at least, not without the use of plugins) but are now a reality.

In this talk, my teammate Eric guides you through the bleeding edge of HTML5, focusing on solving many real-world problems. You’ll learn about media streaming, device input, modern CSS design, media capture, file I/O and more.

Screenshot

Workflow

For Web App Developers

Tooling for the Modern Web App Developer, Addy Osmani

Whether you’re using JavaScript or CoffeeScript, LESS or Sass, building an awesome Web application these days usually requires a plethora of boilerplates, frameworks and tools and a lot of glue to get them to work together. In short, you need a kick-ass utility belt.

In this talk, you’ll get an overview of the current tooling eco-system for the front-end and learn about a new tool that tries to bring together all of the pieces of this eco-system for you, called Yeoman.

Screenshot

An extended version of this talk is also available.

For Web Designers

A Modern Web Designer’s Workflow, Chris Coyier (Video)

A lot is expected from today’s Web designers. If this role defines what you do, then it’s now not just about visual design, but increasingly about building interactions. Designs need to work across different devices of varying shapes, sizes and connections, and they also need to be accessible.

As a designer, you often need to communicate and share code across teams and be familiar with many different technologies. In this talk, Chris Coyier discusses many of the amazing tools that can help things along, discussing what does what and giving a high-level view of a modern workflow.

Screenshot

For Mobile Web Developers

Mobile Web Developers Toolbelt, Pete Le Page (Video)

Building for the mobile Web requires a different mindset to the one we use when developing for desktop, and a different set of tools. Thankfully, a number of great options are available. From remote debugging to emulation, mobile browsers are offering more and more tools to make our lives easier.

In this talk, Pete Le Page takes you through a couple of tools that you can use today to make cross-platform mobile Web development easier, and then he peers into the crystal ball to see what tools the future may bring.

Screenshot

For Debugging

Secrets of the Chrome DevTools, Patrick Dubroy (Video)

Google Chrome Developer Tools provide powerful ways to understand, debug and profile Web applications. Most developers are familiar with Chrome’s basic inspection and debugging tools, but some of its most valuable features, like the Timeline and memory analysis tools, are less known.

In his demo-based walkthrough, Patrick Dubroy provides an overview of Chrome Developer Tools and an in-depth demonstration of some lesser-known features.

Screenshot

The Future

CSS

The CSS of Tomorrow, Peter Gasston

In this talk, Peter looks briefly at the state of CSS3: what you can do right now, and what you’ll be able to do in the very near future. He then looks into the long-term future, to a time when CSS3 will make possible page layouts far richer and more dynamic than we’d thought possible, and when CSS3 has taken on aspects of programming languages. This is effectively what CSS developers will be learning years from now.

Screenshot

JavaScript

The Future of JavaScript, Dave Herman

The Web platform is growing, and JavaScript is growing along with it. EcmaScript 6, the next edition of the JavaScript standard, is gearing up to be a huge step forward for Web programming. In this talk, Dave Herman discusses the exciting new features being worked on for EcmaScript 6 and how they can be used.

Screenshot

Web Applications

Web Components and the Future of Web App Development, Eric Bidelman

Web components are going to fundamentally change the way we think, build and consume Web apps. ShadowDOM, Mutation Observers, custom elements, MDV, Object.observe(), CSS — how do they all fit together?

This talk prepares you for the future of the Web platform by discussing the fundamentals of Web components and how we can use them today with frameworks such as AngularJS.

Screenshot

CSS

State of the Art

All the New CSS Hawtness, Darcy Clarke

This talk dives into some of the latest CSS implementations and specifications floating around. You’ll learn what’s here and what’s around the corner, and you’ll gain insight into why these new features will change our development workflow.

Darcy Clarke touches on modules such as paged-media, multi-columns, flex-box, filters, regions, box-sizing, masking and 3D.

Screenshot

Modularity

Your CSS Is a Mess, Jonathan Snook

We all think that CSS is easy. Take some selectors, add some properties, maybe a dash of media queries, and — presto! — you have a beautiful website. And yet, as the project changes and the team grows, we see the frustration build, with increasingly complex selectors and overuse of !important.

In this talk, Jonathan looks at common problems and solutions that will make your CSS (and your projects) easier to manage and easier to scale.

Screenshot

Pre-Processors

CSS Pre-Processors, Bermon Painter

If you haven’t jumped on the pre-processor train this year, you’re missing out. In this helpful overview of (current) popular pre-processors, Bermon Painter takes you through Stylus, LESS and Sass, with features subdivided into easy-to-learn sections of beginner, intermediate and advanced. I’ve been using mixins quite heavily this year, and I simply wouldn’t have been able to if it weren’t for projects like Sass.

Screenshot

Documentation

A Better Future With KSS, Kyle Neath

Writing maintainable CSS within a team is one of those problems that a lot of people think can be solved by writing CSS in a particular style. But in Kyle’s experience, that never works out.

In this talk, he introduces you to his latest creation, KSS. It’s a documentation and style guide format. He’ll show you why he built KSS and how it’s been helping him at GitHub to refactor its four-and-a-half year old CSS, and he’ll give you a glimpse into the future of KSS.

Screenshot

JavaScript

The Importance of Code Style

Maintainable JavaScript, Nicholas Zakas

Some say that good code is its own documentation, and the fact is that the more readable our code is, the easier it is to maintain.

Writing JavaScript for fun and writing it professionally are two different things, and in this talk by Zakas, you’ll learn practices to make JavaScript maintainable over the long run, to reduce errors and to make your code easily adaptable to future changes. It’s highly recommended reading.

Screenshot

A Modern Large-Scale App Stack

SoundCloud’s Stack, Nick Fisher

I’ve talked a lot about large-scale development in the past. It’s a non-trivial problem that’s difficult to get right, and so it’s exciting when someone working on such challenges shares their experience.

In this talk, Nick Fisher of SoundCloud discusses the company’s story of developing large-scale applications with JavaScript, not only at runtime, but also its steps to make development and deployment easier. In particular, he looks at RequireJS and Backbone, talking about how SoundCloud has used and abused each to suit its needs, sometimes in uncommon ways.

Screenshot

Rethinking Application Structure

Re-Imagining the Browser With AngularJS, Igor Minar

What if you could a write modern Web app with dramatically fewer lines of code and improve its readability and expressiveness at the same time? In case you’re wondering: no, there’s no new language to learn, just familiar old HTML and JavaScript. As a matter of fact, there are concepts for you to unlearn.

AngularJS is a client-side JavaScript Web development framework whose authors believe they’ve done something special. Instead of asking what kind of functions they could provide to make writing apps smoother, they asked, “What if the browser worked differently in a way that eliminates code and gives structure to apps?”

In this talk, you’ll get a tour of how to get the power of tomorrow’s Web platform in today’s Web applications.

Screenshot

Internationalization and i18n

Entschuldigen you, parlez vouz JavaScript, Sebastian Golasch (Video)

While JavaScript applications grow in size and complexity, there are still some white spots on the big map of Web applications: internationalization and globalization! If you´re still thinking that switching strings in and out is the way to go, you are definitely headed in the wrong direction.

In this talk, Sebastian takes you through how to spot real-world internationalization problems and how to solve them in the most elegant way.

Screenshot

I couldn’t cover internationalization without mentioning Alex Sexton, who has also spoken a great deal on this topic. His JSConf talk on client-side internationalization is available in video form if you’re interested in checking it out.

Patterns and Principles

The Plight of Pinocchio, Brandon Keepers

JavaScript is no longer a toy language, and many of our Web applications can’t function without it. Brandon states that if we are going to use JavaScript to do real things, then we need to treat it like a real language, adopting the same practices that we use with real languages. I completely agree with him.

This framework-agnostic talk takes a serious look at how we develop JavaScript applications in the real world. Despite their prototypical nature, good object-oriented programming principles are still relevant. The design patterns that we’ve grown to know and love work just as well in JavaScript as they do in any other language.

Screenshot

When to Lazy Load Scripts

How Late Is Later?, Massimiliano Marcon

Reducing the loading time of a Web application is a well-known challenge. Developers need to make sure that the browser downloads only the code that is strictly necessary to bootstrap the application, and leave the rest for later. This is what we commonly call “lazy loading.”

But when is “later”? When is the right time to lazy load? This talk shows how JavaScript code — functions and objects — can be delivered to the browser on demand, thus reducing the perceived loading time of a Web application.

Screenshot

Mobile

Building Touch-Based Interfaces

Creating Responsive HTML5 Touch Interfaces, Stephen Woods (Video | Audio)

Flickr front-end engineer Stephen Woods shares some hard-learned lessons about building responsive touch-based interfaces using HTML5 and CSS. Because our users are demanding better instant feedback from touch-based UIs, understanding how to approach this problem and avoid the pitfalls will be critical for many application developers in the future.

Screenshot

The Challenge With Scrolling

Embracing Touch: Cross-Platform Scrolling, Mark Dalgleish (Video)

Scrolling effects are a popular way to add personality to the simple act of moving down the page. Unfortunately, these effects don’t work natively on mobile devices, where the touch interaction would make these techniques more effective. In this talk, Mark looks at some ways to implement these effects within the limitations of mobile browsers.

Screenshot

Native, HTML5 and Hybrid Apps

Native, HTML5 and Hybrid Mobile Development, Eran Zinman

One of the toughest decisions every mobile developer faces is choosing a development strategy: “Should I develop a native, HTML5 or hybrid mobile app?” Over the past two years, Eran has led Conduit’s mobile client development efforts, experimenting with cross-platform development in various flavors: from complete HTML5 solutions (using PhoneGap and other technologies) to hybrid solutions to semi-hybrid solutions to fully native solutions.

In this talk, Eran shares some real-life experiences in cross-platform development, describing changes that Conduit has implemented along the way, and sharing what some of the “big players” (such as Facebook, LinkedIn and Twitter) are doing in their mobile app development.

Screenshot

Performance, Distribution and Facebook on HTML5

On the Future of Mobile Web Apps, Simon Cross

Simon looks at Facebook’s experience with and investment in the mobile Web, the issues affecting mobile Web developers and what Facebook and the industry are doing to push the mobile Web forward. Mark Zuckerberg’s comments on HTML5 were undoubtedly one of the most discussed topics in mobile this year, and I personally found these slides a good summary of Facebook’s current take on what works and what still requires improvement.

Screenshot

Tools for Mobile Debugging

Mobile Debugging, Remy Sharp

Debugging Web apps on mobile devices can be a genuine pain. Luckily, a number of tools are available today to ease the process. From remote debuggers to cross-device consoles, this talk summarizes the current state of debugging for mobile, going into more depth on debugging than Pete’s talk from earlier in the post.

Screenshot

Responsive Design Techniques

Responsive Web Design: Clever Tips and Techniques, Vitaly Friedman

Responsive Web design challenges designers to apply a new mindset to their design processes and to the techniques they use in design and coding. This talk (by Smashing Magazine’s own Vitaly Friedman) provides an overview of various practical techniques, tips and tricks that you might want to be aware of when working on a new responsive design project.

Screenshot

Web Apps

Offline Web Apps

Offline Rules, Andrew Betts (Video)

In the last couple of years, a deluge of new offline storage technologies have appeared. In this talk, Andrew looks at why they are all excellent and rubbish at the same time and why you need to use all of them, and he walks through techniques to consider when building a Web application that can load and function with no network connectivity.

But making use of client-side storage is necessary not only in order to make an app that works offline, but it can also hugely improve the experience of your website when the user actually does have connectivity.

Screenshot

State of the Art

Building Web Apps of the Future: Tomorrow, Today and Yesterday, Paul Kinlan (Audio)

The browser is an amazing runtime that can already deliver amazing apps. Paul dives into the technologies that will help you deliver Web apps that will blow your users’ socks off now and in the future.

Screenshot

Client-Side Storage

Storage in the Browser, Andrew Betts

Installed native applications can use all the space they want, but in the browser we’re much more limited. This talk explores how to make the best use of the storage technologies available to Web apps, comparing the virtues of different packaging and encoding techniques, and covering simple forms of in-browser compression that can yield surprising results.

As more apps are developed to surf over network turbulence, and to work even when completely disconnected from the network, local storage becomes ever more important.

Screenshot

Application Cache

Application Cache: Douchebag, Jake Archibald (Video)

The Application Cache is one of the cool bits of HTML5. It allows websites to work without a network connection, and it brings us much closer to native app-like behavior. However, from roundup articles and talks about HTML5, you might be left with the impression that it’s a magic bullet. Unfortunately, it isn’t; the Application Cache is, as Jake famously puts it, a douchebag.

In this talk, he looks at how to use the features of Application Cache without the horrible side effects, comparing techniques that you’d use for both a simple client-side app and a large content-driven website. He explores the many gotchas left out of most articles about Application Cache and discusses how to build your website to survive them.

Screenshot

Performance

CSS

High-Performance CSS, Paul Irish

Paul dives into the tools available in and outside of the browser to assess the performance of your CSS. Find out what’s slow (is box-shadow causing paints to be 70 milliseconds longer?) and how to fix it. Learn about about:tracing, CSS profiling and speed tracer, and get a better understanding of the browser’s internals in the process.

Screenshot

There’s also Jon Rohan’s talk about some problems related to CSS performance that were solved at GitHub. Recommended reading.

GitHub’s CSS Performance, Jon Rohan

Screenshot

Avoiding Jank

Jank-Free: In Pursuit of Smooth Web Apps, Tom Wiltzius

Building beautiful experiences on the mobile Web takes more than a good designer and fancy CSS: performance is critical for a Web app to feel fluid. Smooth animation that never drops a frame can give your app a native feel. But when animations stutter, effects lag or pages scroll slowly, we call that “jank.” This talk is about identifying jank and getting rid of it.

Screenshot

Web

Building Faster Websites, Ilya Grigorik

In this comprehensive crash course, Ilya Grigorik shares some really juicy tips on how to make the Web faster, including Google’s findings on what slows down people’s Web experience and how Chrome and other services have improved it. If you’re an engineer looking to improve the performance of your websites or apps, this talk comes highly recommended.

Screenshot

JavaScript

Breaking the JavaScript Speed Limit With V8, Daniel Clifford

Are you interested in making JavaScript run blazingly fast? If so, this talk looks at V8 under the hood to help you identify how to optimize your JavaScript. Daniel shows you how to leverage V8’s sampling profiler to eliminate performance bottlenecks and optimize JavaScript programs. He also exposes how V8 uses hidden classes and runtime-type feedback to generate efficient JIT code. A very interesting talk for performance junkies.

Screenshot

Note: Some of the optimizations mentioned in this talk are specific to V8 and may not apply to other JavaScript engines. I wrote about how to write memory-efficient JavaScript on Smashing Magazine recently, in case you’re interested in exploring the topic further.

Testing

Understanding Code Smells

Why Our Code Smells, Brandon Keepers (Video)

Odors exist for a reason, and they are usually trying to tell us something. If our code smells, it might be trying to tell us what is wrong.

Does a test case require an abundance of setting up? Maybe the code being tested is doing too much, or it is not isolated enough for the test? Does an object have an abundance of instance variables? Maybe it should be split into multiple objects? Is a view brittle? Maybe it is too tightly coupled to a model, or maybe the logic needs to be abstracted into an object that can be tested?

In this talk, Brandon walks through code from projects that he works on every day, looking for smells that indicate problems, understanding why the smells are there, what the smells are trying to tell us, and how to refactor them.

Screenshot

Current State of the Art

JavaScript Testing: The Holy Grail, Adam Hawkins (Video)

Adam talks about this Holy Grail for JavaScript developers: getting a test suite up and running fast and having multiple browsers execute the tests. Getting the Holy Grail is difficult, though, even though several tools have been created in the past in attempts to solve this problem.

Barriers to entries are everywhere. How easy is it to get going testing small parts of JavaScript functionality? What happens as your become bigger and more complex? What about headless testing? Does this process scale up to CI? Can you even do this stuff locally?

A myriad of testing tools and solutions are available, and Adam shows what’s out there and what we as a community need to do next to get the Holy Grail, to ensure a better Web experience for everyone.

Screenshot

Tip: One tool for testing that I’m loving at the moment is Testling-CI, which runs browser tests on every push.

Improving the Testability of Your Code

Writing Testable JavaScript, Rebecca Murphey (Audio)

It’s one thing to write the code that you need to write to get something working; quite another to write the code that you need to write to prove that it works — and to prove that it will continue to work as you refactor and add new features.

In her talk, Rebecca looks at what it means to write testable JavaScript code.

Screenshot

Conclusion

Time spent thinking about (and developing) your craft is time well spent. The more honed your skills are, the more opportunity you will have to become an efficient engineer.

While this list doesn’t cover every excellent talk presented this year, it hopefully offers some direction for you to accentuate your skills. Do consider reading through a few of them. Focused reading in this way will add to your value as a craftsperson and hopefully improve your daily development workflow.

With that, do enjoy the holiday season and have a fantastic new year.

(al)

© Addy Osmani for Smashing Magazine, 2012.

0
Your rating: None

  

Editor’s note: This is an introductory article about a book idea to be published by Smashing Magazine with Chris Heilmann. Check out what we propose as an idea — explaining a way to reconsider how we build websites to ensure they are leaner and more future-proof. At the end of the article, we’d ask you to fill out a quick survey to show your interest.

The Web as it is now is suffering from an obesity problem. If you surf the Web on a flaky mobile connection or some hotel wireless, you’ll find yourself a lot of times staring at a page or app that doesn’t do anything and doesn’t tell you what is going on either. The spinner in the tab or the URL bar seems to be the thing that gets the most mileage in browsers. Surfing with a net tab open in your developer tools shows you an incredible amount of data being sent for seemingly very simple end products.

Why is that? Shouldn’t years of Web development and advocacy about performance by Yahoo and Google and many others have born fruit and made us aware of how much each HTTP request costs? If you look at the final products, it doesn’t seem that way.


Image Credit: seelensturm.

Reasons For An Obese Web

There are a few reasons why our Web is on the chubby side, and most of them actually are possible for us as developers to change.

We Don’t Develop in Realistic Environments

Probably the main reason is that as developers, we work on fast and big computers connected to a fat line, and the first time someone tests our products on slow connections is during quality assurance (QA). And as QA is the first thing to get ditched when deadlines are not met, sometimes this never happens at all.

Clinging On to the Past

Another reason for the love handles on our Web products is a false sense of allegiance to outdated and old technology, namely browsers of the ’90s that refuse to go away. There are many attempted solutions to the problem of legacy environments, each of them with its own problems. The fact is that there are a lot of end users out there on terribly outdated computers with — in our view — bad browsers and probably limited connections. These users should not be blocked out, but they should also not dictate what we build.

Browser Differences

Another big reason is the annoyance of browser differences. There are not many Web technologies and APIs where all browsers are in agreement when it comes to supporting them, and many times we need to repeat code and fork and test to give the same functionality to all of them.

Embracing The Chaos And Celebrating Differences

The last point is the main mistake we make: instead of embracing the chaos that is the Web and our end users’ environments and abilities, we don’t seem to be able to give up on the dream of having a product that works and looks exactly the same everywhere.

My Browser Isn’t the World?

In the worst case, we try to achieve this by blocking out all the browsers we don’t like and proclaiming proudly that “everybody uses browser X and whoever doesn’t is an enemy of the modern web.” This, of course, is just lying to ourselves, and is based on the fleeting concept of a “modern web.” A lot of the most terrible web-based products out there were built years ago to only work in Internet Explorer (IE) 6, which was the bee’s knees at that time. It does not matter which cool hardware has a hardwired browser that is hot right now — we are making the same mistake again if we only build to one browser and lock out others.

Locking out any browser means actually writing more code to test for browsers, and it is almost impossible to reliably detect which browser is in use. If you want proof, just take a quick look at the user agent string of the Yandex browser, which contains the names of almost every browser engine out there:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.5 (KHTML, like Gecko) YaBrowser/1.0.1084.5402 Chrome/19.0.1084.5402 Safari/536.5

I hope we can agree that building for one browser (or engine) only works for you if you are targeting a certain market and group, and even then you are not safe from losing them in the near future.

Libraries Are The Future

Another attempt to achieve the dream of cross-browser uniformity is a strategy of abstraction, using libraries, polyfills and frameworks to allow us to write in one language and have all the browser-difference magic happen under the hood. For production use, this is a very good idea. In the long run, libraries should get us where we want to be — almost every software environment, sooner or later, is running using libraries that unify the access to hardware or data APIs. For app development, we need to define and nurture these libraries and use them to our advantage.

Built-In Redundancy

The issue we have now, though, is that libraries and abstraction frameworks are becoming the starting point, and in the case of simple websites with a bit of extra flair, they are not needed. We just started to use them without considering their impact or even forgot how to do things without them. And in many cases, a lot of the things we do with them are already available in the browser for us, we just need to use what is there instead of simulating it. Libraries themselves start to suffer from obesity, and in a lot of cases, the extra fat is the functionality to make legacy browsers do things they were never meant to do but that browsers based on the HTML5 specification have already built in.

Death By A Thousand Plugins

Misuse of abstraction of code is rampant these days. We use libraries and converters that allow us to write the least amount of code possible to achieve a lot. This comes with a price. The three lines we write in an abstracted language can result in dozens after conversion to browser-understandable code. It is very tempting to use 20 small scripts on our pages when all of them are just a few lines, but this amounts to a mass of HTTP requests and generated code that chokes the browser. As we never see this code, it doesn’t appear to be our mistake — we just wrote the least amount of code possible. Surely adding yet another script with just five lines of code can’t make a difference?

So this is where we should start thinking harder about what we do right now. We’ve become dependent on abstractions for the most simple things and follow a cult of adding lots of helper tools, as they make things much simpler and are needed for a product to be maintainable and able to grow. A lot of the best practices in Web development were found and defined by large companies who had to build products that are maintained across different countries and teams and have to stand up to the requests of millions of users. What is a best practice for the Yahoo homepage or Gmail does not necessarily have to be what makes your smaller product most effective.

Jonathan Snook has a great example of this when he talks about his SMACCS approach to writing CSS. He points out that almost every product starts with a reset.css file, but once finished, removing that file doesn’t show any difference at all because for the elements we use we do define the margin, padding and sizing.

A Vanilla Diet For The Web

So here is what I propose: we need to put the Web on a diet, using vanilla Web technology that comes with browsers. As Alex Russell put it in his talk at Fronteers this year, if we want to change the Web it is up to us to move it ahead, and using polyfills and libraries is a future tax we currently pay.

Every successful diet is connected with a change in lifestyle. For the Vanilla Web Diet, here is what I propose we can do to slim down the products we build. This will not be applicable to everything, of course, and there is a place to start with a library and an abstraction layer. As I said before, sooner or later we will have an environment where libraries allow us to build great apps and products. But for a simple website with a few enhancements, it is time we stop randomly putting things together because they look shiny or seem very small.

The principles of a vanilla Web diet:

  • Build on what works
    Our base layer should be HTML, plain and simple and doing the thing the product is meant to do. Something that looks like a button but doesn’t do anything is not helping our users. When everything else fails, HTML is the thing users get — let’s not deprive them of that.
  • Lack of support is an opportunity
    If an old browser cannot do something, it allows us to test for that and not give it that functionality. In 99% of cases, the functionality is a nice-to-have and not needed.
  • Browser-specific code cannot be trusted
    Every functionality you make dependent on browser-prefixed code adds to the landfill of code that breaks very, very soon.
  • Use a mix of technologies — each for what it does best
    It is very tempting to do everything in JavaScript, but it is not needed.
  • Ask questions
    Whatever you do should be wrapped in an “if,” making sure that only environments that can apply what you want get it.
  • Write as much as needed, not the least possible
    Let’s think about what we write before we write it, instead of adding lots of small, quick solutions.
  • It is not about what you can add — it is about what we can’t take away
    Basic functionality should always be there.
  • Usefulness beats consistency across browsers
    Instead of giving everyone the same experience, always consider what is the best way to ensure people can use what we build.
  • Load only what is needed
    Why should a browser get a library or a data file if it cannot do anything with it?
  • Analyzing effects beats adding FX
    If you want to add shiny things, make sure they can perform in a shiny fashion; nobody likes their browser to slow down for a laggy effect.
  • Strong foundations beat a possible future addition
    A lot of times we add a lot of code and interfaces to allow for a future that will need them. This future hardly ever comes about. Let’s build for the now.

A Quick Example: Adding A Video To A Website

Let’s take a simple example: adding a video to a page. Conditioned and burdened with years of Web development, our thinking might be:

  • HTML5 video is nice, as it is native to the browser, the controls are readily accessible and I could build my own controls using the JavaScript API that comes with it.
  • Older versions of IE, however, don’t play any HTML5 video, so I need to add a Flash fallback.
  • Furthermore, not all browsers support MP4, so I need to have the video in two formats, MP4 and WebM, as well as OGV if I want to support even older Firefox and Opera.

With these in mind, we’ll probably get a video player from GitHub and use that one. The video player would be clever enough to recognize what the current browser supports and write out a Flash video or a native video. It will not help with the codec and browser support issue, unless we also use a player that detects that and sends the correct format, like Vid.ly.

That makes everybody happy and ensures everyone can see the video, right? True, but it also adds a lot of overhead that is really not needed. Let’s think about the use cases here:

  • If I am on an old browser, do I want to load a JavaScript library, have some detection happening and get a Flash player? What if I have no Flash? I loaded a library for nothing and I still cannot get to the video at all.
  • If I am on a modern browser, I loaded a library, and if I have Flash enabled, then I will get a Flash player with all the memory consumption and initialization overhead (granted, this isn’t much, but on my MacBook Air for example, the fan mostly starts because of Flash).

A vanilla diet approach to this would be the following:


	
	
	
		Frolicking hedgehogs
	
	Click image above to download video

HTML5 video-capable browsers will show the video, and others will get an image preview linked to the video. This way, users on old computers and bad connections or browsers without HTML5 video capability will get an image and can watch the movie in the video app of their operating system. They can even do something else while the video is downloading instead of staring at a “buffering” message.

Is is too much work to have the video in two formats? Fine, use one and move the link out of the video tag — that way you offer the option to download the video to everyone on flaky connections:

 

	Frolicking hedgehogs

Download video (MP4, 3MB)

Don’t want your video to be downloadable? Use Flash or Silverlight. This will not stop anyone dedicated enough to download it, but it makes sure you’ve done your part in securing the content. It blocks quite a few potential customers and readers, though.

Another Example: Expandable News Items

A lot of times we use a JavaScript library to have some headings that, when clicked or rolled over, show some paragraphs below them. jQuery’s show() and hide() are meant for that and there are a myriad of plugins to give us that functionality.

If you want to do this in a vanilla Web diet way, there is no need for JavaScript. Let’s start with the HTML. There are many right and wrong ways to do this — lists, definition lists, headings and divs and so on. Many an hour was wasted on forums discussing what the perfect markup is for this. Taking a leaf out of Nicole Sullivan’s book, let’s apply some OOCSS and make ourselves independent of the element names by adding classes:


	Interesting news	
	

Amazing stuff happened

Now, in order to make these collapse and expand in a smooth way, all we need to do is apply some CSS:

.collapsible .content {
	overflow: hidden;
	max-height: 0;
	opacity: 0;
	transition: 1s;
}
.collapsible:hover .content,
.collapsible:focus .content {
	max-height: 200px;
	opacity: 1;
}

Here you can see some of the principles in action. Older versions of IE do not understand max-height or opacity, so they will never apply the styles that hide the content. The much larger max-height of the hover and focus states makes sure that the browser expands the content all the way (it will always go to the real height, the only problem you will have is when the content is higher than 200 pixels, so this is something to point out to whoever is maintaining the code). The transition of one second makes sure the browser does this smoothly instead of just showing the content. Browsers that don’t support transitions still show and hide the content. You can add browser-prefixed transitions, too. Firefox and IE10 already dropped the prefix for transitions and others will follow.

Now, if you want to add onclick functionality to the header, we need some JavaScript. First of all, though, we change our CSS to look for a class on the collapsible element instead of relying on hover. We also make the hiding dependent on a JavaScript class as we don’t want to hide the content in browsers that don’t fulfill all the requirements of our script.

.js .collapsible .content {
	overflow: hidden;
	max-height: 0;
	opacity: 0;
	transition: 1s;
}
.js .collapsible.show .content {
	max-height: 200px;
	opacity: 1;
}

When the user clicks the header, we want to add the class of show to the collapsible element, and then remove it the next time the user clicks. For this, all we need is a single event handler on the document. To remove and add the class, we could change the className property, but newer browsers have the much more flexible classList implementation. We test for the things we use in an if statement and end up with not much code at all:

if (addEventListener && 'classList' in document.body) {
 document.body.classList.add('js');
 document.addEventListener('click', function(ev){
   var t = ev.target;
   if (t.classList.contains('trigger')) {
     t.parentNode.classList.toggle('show');
   }
 }, true);
}

Older versions of IE don’t understand addEventListener(), so this will not be executed as we test for its existence. If classList is supported, we apply a click handler to the document. We then test for and toggle the show class to trigger the CSS change using classList whenever the element with the class trigger is clicked.

More?

Now here’s the idea: I am planning to write a book about this, published with and by Smashing Magazine. I really believe that there is a lot to be said about the things in HTML5 that browsers now give us and that allow us to write simple and effective code to release pragmatic products instead of adding a lot of code we just don’t need for what we want to achieve.

If you are interested, quickly fill out the survey below or drop us a comment and we’ll go ahead.

© Christian Heilmann for Smashing Magazine, 2012.

0
Your rating: None

  

We have a delicate and useful icon set for you, again. Dutch designers from Dutch Icon created a new set of 42 Pika-style vector icons, released with Smashing Magazine for the Web design community. The icons are available as PNG (in two sizes) and AI source files. The icons are released under a Creative Commons Attribution license.

Smartphone

You may be looking to brighten up your checkout page with a more original shopping cart icon or perhaps you’re designing a website from scratch that requires a shrimp icon. Either way, if your budget is limited and you need a wide array of different icons, this set of chunky pixel-perfect icon might be just what you need.

The icons are licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported license. You are free to distribute, transform, fiddle with and build them into your work, even commercially. However, please always credit the original designer of the set (in this case, Dutch Icon).

Download The Set For Free!

You can use this icon set freely for commercial and personal projects. Please link to this release post if you want to spread the word.

Free Icon Set

Description

The set contains 42 icons for various occasions. Each icon is available in two sizes: its original size, 60×60px and 30×30px. The Adobe Illustrator vector file is provided in the set as well. The icons included are:

  • Smartphone
  • Book
  • Light Bulb
  • Map
  • Watch
  • Navigation System
  • Trees
  • Banknote
  • Comment
  • Binocular
  • Laptop
  • Archive
  • Download
  • Upload
  • Delivery Van
  • Fax Machine
  • Tablet
  • Repeat
  • Dashboard
  • Like
  • Revenues
  • Silverware
  • Video Camera
  • Move
  • Fire
  • Shower
  • Checkmark
  • Delete
  • Folder
  • View
  • Calendar
  • Spaghetti
  • Shrimp
  • Global
  • Location
  • Computer Screen
  • Plug
  • Previous
  • Next
  • Eraser
  • Shopping Cart
  • Remove From Cart

Behind The Design

As always, here are some insights from the designer:

“Pretty Pika! A new chunky pixel-perfect and vector-perfect icon style has been born. She loves tiny integration, looks gorgeous on Retina displays and covers all major themes. And (very) soon to be a semantic symbol font. We wouldn’t want you to miss out and only hope you enjoy her as much as we do.

We are happy to provide designers and developers with an original and crafted icon design. Use visual language to make your graphic applications or identity design look sharp. “

— Dutch Icon

Thanks, Dutch Icon! We sincerely appreciate your time and efforts!

(jc)

© Smashing Editorial for Smashing Magazine, 2012.

0
Your rating: None

  

Editor’s note: Welcome to a new column in the UX Design section on Smashing Magazine! Each month we’ll pick a handful of popular questions asked by our readers around good practices in designing smart and usable experiences. They will be answered by Christian Holst, a regular author here on Smashing and founder of Baymard Institute. Prior to co-founding Baymard Institute in 2009, he worked as a usability engineer in the hearing aid, credit card and consulting industries.

Adaptive Layout Vs. Responsive Layout

In which kinds of sites/projects is it better to use an adaptive layout (fixed break points)? In which kinds of sites is it better to use a responsive layout (fluid grids)?

A responsive layout[1] is in theory always better than an adaptive layout, but in some cases an adaptive layout is a more pragmatic solution.

An adaptive layout will give you more control over the design because you only have a handful of states to consider. In a responsive layout you easily have hundreds of states — sure, most of them with very minor differences, but they are different nonetheless — which makes it harder to know exactly how your design will look. This makes a responsive layout more difficult to test and predict with absolute certainty. That said, this is also the beauty of a responsive layout. By allowing some uncertainty on a superficial level, you gain certainty on more fundamental levels. Sure, you can’t predict with pixel-perfection how the design will work in a 943 × 684 pixel viewport, but you can rest assured that it works well — that the fundamental features and layout structures are meaningfully deployed.

An adaptive layout has its merits because it can be a more pragmatic solution that is cheaper to implement and easier to test. An adaptive layout can be considered the cheaper sibling of a responsive layout and can thus be appealing if resources are tight. This is especially true when dealing with an existing website, where a complete rewrite is not always feasible. In such cases, an adaptive layout can be a good (and more manageable) start. Dan Cederholm argues this case well in his article “Adapted”.


Image source: Trent Walton.

One argument often brought up in favor of an adaptive layout when compared to a responsive layout is that of typography — in particular better control over line lengths and avoiding orphaned header text. Trent Walton has jotted down some good thoughts on the matter. In essence, by changing font sizes (this is easy when using em), you can ensure readable line lengths (50-75 characters per line) in your responsive layout. This leaves the issue of potentially orphaning header text. While one may argue that this is the nature of the web, there are cases where seeking maximum control over a page headline makes sense. In these cases, using a plugin like FitText comes to our rescue, allowing us to avoid orphans.

[1] The definitions of responsive design and adaptive design are manyfold. Jeffrey Zeldman argues that restricting the term responsive design to a technological approach may prove too limiting and that the overall goal is device agnosticism, and we should thus include fixed breakpoint designs in our definition of responsive (web) design. Moreover, Aaron Gustafson defines adaptive design as “creating interfaces that adapt to the user’s capabilities (in terms of both form and function)” with responsive design as a subset meaning “fluid grids, fluid images/media & media queries.” In this answer I’ve intentionally limited the scope of discussion to layout, hence the use of responsive layout and adaptive layout. The definitions presented in the question are used throughout the answer, namely that responsive layout equals fluid grids, and adaptive layout equals fixed breakpoints.

User Interface (UI) Consistency Across Devices Vs. Device-Specific UI Conventions

In designing a product that will span various devices (i.e. Netflix or Pandora), what’s more important: consistency of the brand and UI, or designing to appropriately follow the guidelines of that specific device (i.e. designing a common experience on the iPhone, Android, television, Xbox)?

There are three important factors you need to consider: your focus (as a business), how familiar your users are with your UI, and how different your UI and functionality are on different platforms.

  1. Focus: There may be branding reasons to keep a consistent UI across your platforms, perhaps especially for lesser-known brands that are still fighting to establish an identity in the minds of their customers. However, users are typically more familiar with the device-specific UI conventions than those of a brand. Jakob Nielsen often states, “Users spend most of their time on other sites,” and while we’re not just talking about websites here, it is much the same principle (on a smartphone, simply replace “sites” with “apps”).
  2. Familiarity: Are most of your users spending hours a day using your service? Have they used it for a long time? Or are the majority of your users infrequent or newly acquired? Let’s say you have a business or productivity service and you know the majority of your users spend lots of time in it all year long. In this case, familiarity across the applications trumps device UI conventions, because the user has invested a significant amount of time learning your unique UI. On the other hand, if users haven’t spend that much time with your services and haven’t built strong cognitive and emotional ties to your designs and features, then device-specific UI conventions will generally result in better usability.
  3. Functionality: This has two aspects: a) Is your service only solving a single problem with a single feature, or is it more advanced? and b) Is there a difference in functionality and features across the various devices? If the features you offer on different platforms vary greatly, then adhere to device UI conventions, since cross-platform consistency will yield little benefit in terms of usability (using the same branding and general aesthetic design won’t help the user if the features are widely different — in fact, they could potentially cause harm as the user will think there’s overlap when in fact there isn’t). On the other hand, if you’re solving a single, simple problem, then diverging from device UI conventions is okay since users will very quickly learn your unique UI and you’ll potentially be able to solve the UI problems specific to your feature more readily than the generic device conventions afford.

In short: sticking to device-specific UI conventions where appropriate is a good, if slightly simplistic, rule of thumb.

Balancing Usability Research With Unique And Creative Concepts

How should I balance research, user feedback and usability testing with personal experience, instinct and trying to create a creative, unique, compelling experience? Basically, how much should users influence or guide the solution I am designing? It is “user” experience after all :)

The concept of your product, service, app or website is at the core of your user experience. It’s where you differentiate yourself from the competition and where you create true value to the customer. So develop your concept as creatively as possible and make it as original as possible. Then, when it comes to the real-life implementation, read up on user research, study UI conventions and perform usability testing as much as your concept allows.

Usability research and testing are what make your services easier and more seamless to use (which are truly important qualities in a competitive landscape), but they are not the reason people choose to use a service in the first place — they do that to solve a problem or fulfill a need. So first come up with that ingenious new concept, and then draw heavily on user research when implementing the service.

Usability tools are there to test and validate your designs, allowing you to continuously iterate your design based on user behavior and perceptions — an optimization process that should continue throughout the product’s life cycle.

Optimal Positioning Of Form Field Labels

What’s the best way to position form labels for an input field? Above the field, to the left, to the right? What about inline labels?

In short: for most input forms found on the web, such as contact forms, account creation and e-commerce, optimal form usability would be to place the label above the form field. Matteo Penzo’s eye tracking test on form label placement from 2006 confirms this.

On mobile devices the placing the label above the form field will ensure maximum width for the user input.
On mobile devices, placing the label above the form field will ensure maximum width for the user input. To the left you see Macy’s mobile checkout, where placing the label next to the form field results in a field so narrow the test subject couldn’t see the typo in his e-mail address. To the right you see an example of the recommended approach with the label above the form field.

Placing the label above the field is even more important if the form will also be accessed on mobile devices in portrait mode, due to the narrow screen. The user might otherwise have to deal with form fields that aren’t long enough to display the entire input, or end up doing a lot of sideways scrolling and panning between label and field. However, the exact opposite may be true of landscape mode, where the miniscule height of the viewport may be eaten up by the touch keyboard, potentially pushing the active field’s label out of sight.

An exception to placing the label above the field is for long forms that have very frequent and repeat usage, where the user needs to be able to quickly identify a few specific fields in a long list. In such cases, having the labels to the left of the form field makes it easier to scan. The same would go for a pre-filled form where the user needs to edit only a specific set of fields (e.g. when editing account profile information).

An example of inline labels, where the label acts as placeholder text in the form field.
An example of inline labels, where the label acts as placeholder text in the form field.

Inline labels, where the label is placed inside the form field as placeholder text, are horrible from a usability perspective. During our e-commerce checkout usability study, we saw numerous test subjects have serious issues with inline labels in Apple’s checkout process. While the approach makes for a simple visual appearance, the form is very difficult to interact with because each field loses its context the second the user starts typing. In the study, this not only made it more difficult for the subjects to fill out the form fields, it also made it very difficult for them to correct validation errors since the labels were missing.

Note that the importance of optimal positioning of the form field labels (and form field usability in general) are of course closely related to how many form fields the user has to fill in, and how often the user will need to complete the form. If it’s a single-field, single-use newsletter sign-up form, then choose whichever approach and design fits best with your overall layout. (Even inline labels would be acceptable in such a case.) But as soon as you have more than a handful of fields — e.g. a checkout process or a sign-up form that requires an address — I’d strongly recommend that you reduce friction as much as possible by following common form field usability guidelines, such as positioning the labels above the form field.

Any Questions?

If you have any questions that you would like me to tackle for a future Usability Q&A column here on Smashing Magazine, please ask them in the comments below!

(cp) (jc)

© Christian Holst for Smashing Magazine, 2012.

0
Your rating: None

  

Android is an attractive platform for developers, but not all designers share our enthusiasm. Making an app look and feel great across hundreds of devices with different combinations of screen size, pixel density and aspect ratio is no mean feat. Android’s diversity provides plenty of challenges, but creating apps that run on an entire ecosystem of devices is rewarding too.

Android devices in various sizes.
There are hundreds of Android devices with different screen sizes and resolutions. (Image credit: Android Design. Used under Creative Commons license.)

At Novoda, we build Android software for brands, start-ups and device manufacturers. We often work with visual designers who are new to Android. The new Android Design site is the first resource we recommend. You should definitely check it out. However, there is plenty more to pick up! The goal is to create apps that people love to use. Thoughtful UX and aesthetically pleasing visual designs help us get there.

This article provides a set of practical tips and design considerations for creating Android apps. I’ve tried to include something useful whether you’re crafting pixel-perfect graphic assets, finding an optimal user flow or getting your hands dirty developing XML layouts.

Pixels

Visual design is hugely important in the perceived quality of an app. It might even improve usability. Most developers have some exposure to UI patterns, but developers with visual design skills are rare. They really need you. Delivering high-fidelity mock-ups, drawable resources (i.e. graphic assets) and guidance to developers is the best way to deliver an aesthetically pleasing experience to the end user.

Scale Nicely

Android is a platform of many screen densities. There is no set of resolutions to target, rather a density independent measurement scheme for graphics, widgets and layouts. This is covered in depth in a previous Smashing article and the official documentation, so I’ll just add a mention of this neat web tool for calculating density pixels.

Screen densities.
Optimize graphics for different screen densities. (Image credit: Android Design. Used under Creative Commons license.)

It’s not always practical to hand optimize graphic assets for each density. The platform can scale resources down reasonably well. However, it’s always worth testing designs on low-end devices and optimizing resources that scale badly.

Be State Friendly

Touch states provide important confirmation of clicks and selections. When customizing widgets such as buttons, it’s important to create drawables for all necessary states (such as default, focused, pressed and disabled). The focused state is essential user feedback on devices that support directional pad or trackball navigation.

Size is important too. Touch input is imprecise and fingers occlude the UI as they interact with the screen. Touch targets should normally be at least 45 density pixels in width and height.

Use Fonts

Android has two fonts: Droid Sans and Roboto. Roboto was released in Ice Cream Sandwich (Android 4). It’s been compared to Helvetica, but it’s a little condensed, which is great for small screens. You’re not limited to Roboto or Droid Sans, though. Any font can be packaged within an app in TTF format (with some memory overhead).

Roboto font.
Roboto is Android’s new font, introduced in Ice Cream Sandwich. (Image credit: Android Design. Used under Creative Commons license.)

Use 9-patch Drawables

9-patch drawables allow PNGs to stretch and scale nicely in pre-defined ways. Markings along the top and left edges define the stretchable areas. The padded content area can optionally be defined with markings along the bottom and right edges. 9-patches are essential for creating and customizing UI widgets.

Draw 9-patch.
Create scalable widgets with Draw 9-patch.

It’s possible to create 9-patches manually, but the Android SDK comes with an nice, simple tool called Draw 9-patch. This makes it quick and easy to convert a regular PNG in to a 9-patch. It highlights the stretchable area and displays previews of the resulting drawable with different widths and heights.

Handle Design Legacy

Honeycomb (Android 3) and Ice Cream Sandwich (Android 4) modernized Android’s visual design with the Holo theme. However, some device manufacturers have a poor reputation for keeping platform versions up-to-date. Some of today’s most popular devices will never be upgraded to Ice Cream Sandwich.

Meetup screenshot.
The Meetup app makes everybody feel at home with separate Gingerbread (Android 2.3) and Ice Cream Sandwich widgets.

So what can be done? There are two options. Deliver the current look, feel and experience to all devices or use a separate set of widgets styles and drawables for Gingerbread and below. Both approaches are valid. Would your users prefer modern or comfortably familiar?

Showcase the Brand

Sometimes clients fear that sticking to recognized UI design patterns will make their apps less distinctive. I think the opposite is true. As patterns like the action bar become ubiquitous, they fade into the background. Users can spend less time wondering how to use an app and more time appreciating how elegantly your app solved their problem. That experience is much more valuable for the brand than a one-of-a-kind UI for the sake of differentiation.

Color navigation screenshot.
The original Color app had an online FAQ for the UI controls. Make sure that navigation is intuitive.

Branding can be expressed through design of icons, drawables and widgets, as well as in the choice of colours and fonts. Subtle customization of the standard platform widgets can achieve a nice balance of brand values and platform consistency.

Create High-Fidelity Mock-Ups

High fidelity mock-ups are the best way to communicate visual design to developer responsible for implementation. The Android Design website provides templates in PSD and other formats. It’s important to try mock-ups out on real devices to confirm that they feel right, with UI components sensibly sized and placed. The Android Design Preview tool allows you to mirror mock-ups directly from your favourite design software to an attached Android device.

A practical approach for mock-ups is to work against the screen characteristics of the most popular devices. Ideally, create mock-ups for each alternative layout required by screen size or orientation.

Polish

Attention to detail is key. Become involved in the development process to ensure that your designs are realized. As a developer, I would always prefer to work with active designers than those who deliver mock-ups and resources before disappearing into thin air. Designs need to be iterated and refined as the app develops.

Animated transitions provide some visual polish that many Android apps lack. Developers might not include such things on their own initiative. Make them part of the design when they make sense. Aside from transitions, animations are a great way to keep users distracted or entertained when the app needs to make them wait.

User Experience

Android has patterns and conventions like any other platform. These help users to form expectations about how an unfamiliar app will behave. Porting an iOS experience directly to the Android platform almost always results in a poor user experience.

Back buttons in Android and iOS.
Back is a platform affordance in Android. In contrast, labeled back buttons within the app layout are the norm for iOS.

The back button is the best illustration of the interaction differences between Android and iOS. All Android devices have a hardware back button or on-screen navigation bar (including back button). This is universally available as a feature of the platform. Finding a back button within an Android app layout feels weird as an Android user. It makes me pause to think about which one to use and whether the behaviour will differ.

Design User Flows

At the very simplest level, Android apps consist of a stack of screens. You can navigate in to the stack with buttons, action bar icons and list items. The platform back button allows you to reverse out of the stack.

The action bar mirrors a web convention, where the app icon to the left of the action bar usually takes you to the top level of the app. However, there is also the up affordance, intended to take advantage of structural rather than temporal memory. This is represented by a backwards facing chevron to the left of the app icon. This signals that pressing the icon will navigate one level up in the information hierarchy.

Up affordance.
The up affordance allows the user to navigate up an information hierarchy instead of going to the top level of the app.

The purpose of the up affordance might be subtle at first. Android apps can have several entry points in addition to the launcher. The Intent system allows apps to deep link each other and home screen widgets or notifications might take you directly to specific content. The up affordance allows you to navigate up the information hierarchy regardless of where you came from.

Try user flows on potential users with wireframes or mock-ups and iterate. Prototypes on real devices are ideal because they allow you to test in realistic mobile environments. This might seem like a lot of effort, but remember, you only need to try things out with a few users.

Be Platform Consistent

UI patterns are your friend. It’s much better to think of these patterns as tools than constraints. Users would prefer not to have to learn to use your app, so patterns provide familiar hints about how to navigate and interact.

Action bar is the most widely adopted Android pattern. It tells you where you are and what you can do. It’s a native feature of the platform since Honeycomb and the excellent Action Bar Sherlock library makes it available on older platform versions too.


An example of the dashboard and action bar patterns.

The dashboard pattern is also quite widely used. These grids of icons are usually presented to the user when they launch an app. Dashboards provide top level navigation and describe the primary areas of the app.


I worked on the Songkick app, where we used a dashboard draw out the content of the app with full-bleed images.

The  workspaces pattern can be implemented with the ViewPager component. This allows users to swipe screens left and right between content. This can be used in conjunction with tabs to provide a more fluid browsing experience with tabbed data.

ViewPager swiping.
ViewPagers allow users to swipe left and right. Page indicators or tabs make this navigation discoverable.

The ribbon menu is an emerging navigation pattern. This allows us to launch the user directly into content and provide the top level navigation in a menu, which slides in from the left side of the screen when you press up.

Ribbon menu
The ribbon menu is an alternative to dashboard navigation.

Tablet optimized apps often take advantage of multi-pane layouts. A single tablet screen can display the content of several separate phone screens side by side. Optimising for tablets can involve creating several alternative layouts for different screen widths. Sections of UI can be designed once and laid out in different configurations for different screen sizes. Multi-pane layouts help to avoid overly wide list items and sparse layouts.

Multi-pane tablet layout
The Economist news app uses multi-pane tablet layouts so users can explore the hierarchy of content on a single screen.

These are familiar and proven UI patterns. They’re the best tools for starting to sketch out your app layouts and navigation. However, they shouldn’t discourage you from trying something new. Just ensure that the app behaves predictably.

Design Responsively

Android is a platform of many screen sizes. The devices that I can lay my hands on in our office compose a spectrum of screen sizes from 1.8 to 10.1 inches (as long as we ignore the Google TV). With variable screen area, Android has something in common with responsive web design. There is no getting away from the fact that design and implementation of a responsive experience across the full range of devices takes a lot of work. Supporting every screen is the ideal, but there are also sensible strategies for coping with the diversity of the platform.

Knowing a little about your target users and popular devices can help focus efforts and avoid premature optimisation. A good default strategy is to target popular, middle sized phones (3.2″ – 4.6″) and then optimize as necessary with alternate layouts and user flows for particularly small (<3″) devices and tablets.

It’s always best to be orientation agnostic. Some devices have physical keyboards that require the device to be held in landscape. The on-screen keyboard is also easier to use in landscape. Text entry on touch screens is awkward an error prone, so let’s at least give our users the benefit of the landscape keyboard.

Understand Mobile Interactions

People interact with mobile apps differently from websites or desktop software. Mobile apps rarely have the undivided attention of a user and most interactions use touch input, which is not as precise as we might like.

Mobile interactions can often be measured in seconds. We recently developed a location-based app that allows users to check-in at bars. We counted the clicks on user paths such as check-in, considering whether each step could be avoided or simplified. We specify everything that an app should do as user stories. The most frequent stories should be as quick and easy to accomplish as possible. It’s particularly important in this scenario, because the user might be under the influence of alcohol…

Optimize First Use

First launch experience is crucial. Apps are often installed in response to a real world problem. If the first run isn’t satisfying then the user might never return. If the app requires sign up, offer preview functionality so that users get a feel for the experience. They probably need to be convinced that it’s worth filling out that sign-up form. Also consider using analytics to measure points where users drop off in the launch and sign-up process.

Many apps launch with a tutorial. This is usually an admission that the app is too complicated, but if you’re sure that you need one, keep it brief and visual. You might also want to use analytics to confirm that a tutorial serving a purpose. Are users that complete the tutorial more active? How many users just skip the tutorial?

Bring the App to Play

User experience considerations shouldn’t end in the app. It’s worth putting a bit of thought in to the Google Play Store listing to ensure that it’s immediately obvious what the app does and why the user would want it.

These Graphic Asset Guidelines will help you to create promotional material suitable for the various contexts and scales in which they appear. Some of these graphics are a pre-requisite for being featured too.

Layouts, Styles and Themes

Android has a visual layout editor and it’s getting better all the time. However, I still find myself developing XML layouts by hand. This section gets down to implementation details, covering some best practices for crafting maintainable and performant layouts. Visual designers might want to skim this section, but some awareness of implementation details can’t hurt.

The most general purpose layouts are RelativeLayout and LinearLayout. RelativeLayout should be favoured for efficiency, whilst LinearLayout is useful for distributing space between views using weights. GridLayout was new in Honeycomb. This is useful for creating complex layouts on large screens without nesting. Nesting layouts too deep is bad for performance and code readability alike!

Let the Framework Do the Work

The Android framework provides automated resource switching based on folder structure. This means that you can have separate graphic assets and layouts for different screen sizes and densities by arranging them in the correct folders. It goes much further than that. For example, you could switch color resources for different platform versions or even animation durations for different screen sizes.

Resource folder structure.
The framework provides automatic resource switching.

Since Honeycomb, it’s also possible to switch resources on available screen width in density pixels. This is a move away from the bucketed small, normal, large and extra-large screen size switching. It facilitates responsive design and allows multiple layout switching points (perhaps switching to a tablet-optimized layout at 600dp with another alternative at 800dp). It’s typical to have multiple layout files with different configurations of the same components for different screen characteristics.

State list drawables make being state-friendly easy. These allow you to specify different drawables for different states of a UI component in an XML file. As mentioned earlier, representing states properly provides important user feedback.

<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item
    android:state_focused="true"
    android:state_pressed="true"
    android:drawable="@drawable/my_button_pressed_focused" />

  <item
    android:state_focused="false"
    android:state_pressed="true"
    android:drawable="@drawable/my_button_pressed" />

  <item
    android:state_focused="true"
    android:drawable="@drawable/my_button_focused" />

  <item
    android:state_focused="false"
    android:state_pressed="false"
    android:drawable="@drawable/my_button_default" />

</selector>

Extract Values

It’s good practice to keep layout XML clean of explicit colours and dimensions. These can be defined separately and referenced in your layouts. Defining colours and dimensions separately promotes visual consistency and makes things easier to change later on. Extracting these values allows switching of dimensions on different screen sizes, orientations and platform versions. This is useful for tweaking padding for small screens or increasing text size for readability on large screens, which tend to be held further away from the face. Perhaps res/values/dimens.xml contains:

<dimen name="my_text_size">16sp</dimen>

whilst res/values-sw600dp/dimens.xml contains:

<dimen name="my_text_size">20sp</dimen>.

Use Styles and Themes

A good technique to keep layout XML maintainable is to separate the styling concern from the positioning concern. Every View in a layout needs to have at least a width and height attribute. This results in a lot of boilerplate, which you can eliminate by inheriting from a set of base parent styles.

<style name="Match">
  <item name="android:layout_width">match_parent</item>
  <item name="android:layout_height">match_parent</item>
</style>

<style name="Wrap">
  <item name="android:layout_width">wrap_content</item>
  <item name="android:layout_height">wrap_content</item>
</style>

<style
  name="MatchHeight"
  parent="Match">
  <item name="android:layout_width">wrap_content</item>
</style>

<style
  name="MatchWidth"
  parent="Match">
  <item name="android:layout_height">wrap_content</item>
</style>

Recurring sets of attributes can be moved into styles. Widget styles that occur almost universally throughout the app can be moved into the theme. If a particular type of button always has the same text color and padding, it’s much cleaner to specify the style than duplicate these attributes for each occurrence.

<style
  name="MyButtonStyle"
  parent="MatchWidth">
  <item name="android:padding">@dimen/my_button_padding</item>
  <item name="android:textColor">@color/my_button_text_color</item>
</style>

We save four lines of attributes when we add the button to a layout. The layout file can be concerned with just the positioning and unique attributes of widgets.

<Button
  android:id="@+id/my_button"
  style="@style/MyButtonStyle"
  android:text="Hello, styled world!">

You can take this further by overriding default button style in a theme and applying it to an Activity or the entire app in the AndroidManifest.xml.

<style
  name="MyTheme"
  parent="@android:style/Theme.Holo">
  <item name="android:buttonStyle">@style/MyButtonStyle</item>
</style>

<style
  name="MyButtonStyle"
  parent="@android:style/Widget.Button">
  <item name="android:padding">@dimen/my_button_padding</item>
  <item name="android:textColor">@color/my_button_text_color</item>
</style>

Optimize

The include and merge XML tags allow you to drop reusable sections of UI into your layouts, minimizing duplicate XML when the same set of views occurs in multiple layout configurations.

<include
  layout="@layout/my_layout"
  style="@style/MatchWidth" />

A relatively new addition to the Android Developer Tools is Lint. This tool scans the resources in a project and creates warnings about potential performance optimizations and unused or duplicated resources. This is incredibly useful for eliminating clutter as an app changes over time and it’s certainly worth checking lint for warnings regularly during your development process.

Debug

Sometimes layouts just don’t turn out how you expected. It can be hard to spot bugs amongst all those angle brackets. This is where Hierarchy Viewer comes in. This tool allows you to inspect the layout tree of an app running in the emulator. You can inspect the detailed properties of each view.

Hierarchy Viewer.
Inspect your layout trees with Hierarchy Viewer. Those colored dots can tell you about your layout performance.

Hierarchy Viewer has a couple neat tricks for visual designers too. It allows you to inspect screens in zoomed pixel perfect mode and export the layers of a layout as a PSD.

Conclusion

So you’ve been introduced to the platform and the tools. What next? Ultimately, the best way to get a feel for Android is to use it every day. The most satisfying app designs have a few things in common: platform consistency, attention to detail and clean visual design. The first two, at least, can be picked up by using and analysing existing Android apps.

Android has come a long way in the last few years. The platform and the apps have become gradually more refined. Functionality is not enough at this point. There are almost half a million other apps out there, and users want polish.

Resources

(jc)

© Jamie McDonald for Smashing Magazine, 2012.

0
Your rating: None