Smashing Magazine Feed

For Professional Web Designers and Developers
  1. Designing CSS Layouts With Flexbox Is As Easy As Pie

      

    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:


    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.


    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.


    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.

  2. Mobile UX Research: Exploring Ten Fundamental Aspects Of M-Commerce Usability

      

    Everyone is talking about mobile. Some e-commerce websites are venturing into it. Mobile commerce (also known as “m-commerce”) has immense potential, exhibiting a 86% growth rate and hitting $25 billion in 2012 (set to reach $86 billion by 2016, according to eMarketer).

    It’s also a whole new platform, with new interaction methods and usage contexts that introduce a host of limitations and pitfalls to watch out for when designing and running an m-commerce website. With few best practices yet established, m-commerce is, to a large degree, unchartered territory when it comes to actual implementation.

    This is why we decided to invest the better part of a year at Baymard Institute to conduct a large-scale usability study focusing specifically on m-commerce (following the “think aloud” protocol). We set out to explore the entire mobile shopping experience, including users’ conceptual understanding of m-commerce websites and how users interact with form fields, category navigation, search, product pages, the checkout process, etc.

    The 18 m-commerce websites that we tested were: 1-800-Flowers, Amazon, Avis, Best Buy, Buy.com, Coastal.com, Enterprise.com, Fandango, Foot Locker, FTD, GAP, H&M, Macy’s, REI, Southwest Airlines, Toys “R” Us, United Airlines, Walmart.

    Despite testing the mobile websites of some of the largest e-commerce players in the world, our subjects encountered 1,000+ usability-related issues during the testing sessions. These usability issues have been analyzed and distilled into 147 design recommendations in a report titled “M-Commerce Usability.” In this article, we’ll share 10 recommendations from that report with you.

    While following some of the guidelines would improve the usability of desktop websites, too, there is a major difference in the severity of breaking them. Whereas these guidelines are largely “nice improvements” on desktop, they are among the “vital basics” to get right on an m-commerce website. Thus, most of these usability guidelines are not exclusive to mobile, but they are much more critical to get right in the m-commerce context.

    1. Make The Home Page Easily Scannable

    Issue: When users are not able to get an overview of the entire website by quickly scanning the home page, they will feel less confident with the website and often end up choosing the wrong path for their task.

    70% of the test subjects scrolled up and down the entire page when first landing on a home page or a category list, in what most described as “getting an overview of my options.” These subjects wanted to see their options before deciding which to choose. Even when they knew how they wanted to find a given product, some subjects still chose to get an overview of the home page, presumably to get a better feel for the website on which they were going to shop. In some instances, when a subject found the category they were looking for, they continued to look through one or two other categories to get a better sense of the other options on the website.


    Most subjects scanned the whole home page to get an overview of their options and to better understand what they could do on a particular website. Here, one subject continued to explore the home page options, even after having found his desired navigation path of “category” → “men.”

    Therefore, making the home page easily scannable is important because this will be the first point of contact for a very large portion of your mobile visitors. This initial impression will have a significant impact on the types of products they expect your website to carry and, just as importantly, not carry. While “easily scannable” might sound a bit vague, three instances of “what not to do” became clear during testing.

    Having Too Many Visual Elements

    Avoid the confusing eye path that results from placing multiple highly graphical elements that demand attention high up on the home page. This was the case on Macy’s, where approximately 60% of the first viewable part of the home page is plastered with highly graphical content, with at least eight different elements calling for attention:


    Multiple subjects were overwhelmed by Macy’s home page because it was very difficult to scan. As one subject expressed it, “I’m desperately trying to get an overview here. There’s so much crap being shoved at my face.” The right-hand image shows typical eye fixations.

    This is not to say you cannot have graphics — but limit their size if they are above the fold on the home page, and design them to have a clear eye path.

    Not Showing the First Layer of Categories

    Another mistake is unnecessarily hiding the category navigation. Some websites have a single “browse categories” option, which takes the user to a new page with the first layer of category choices. If you have a website where the user cannot browse with any method other than category and search (i.e. not by “brand” or “store” directly from the home page) and the number of main category options is of a somewhat manageable size, then this is an oversimplification. Instead, show the first level of category options directly on the home page so that users can start scanning the list immediately upon landing on the home page.


    On the left: On Coastal.com, all the category options are displayed directly on the home page, which not only allows direct access, but gives users an accurate idea of the types of products they can expect to find on the website. For stores with multiple ways of browsing the catalog (e.g. by both “category” and “brand”), displaying the category options directly on the home page might not be feasible. On the right: For stores with a very high number of first-layer categories (typically mass merchants), a curated list with the most popular options might prove to be a better option, because displaying all categories would impede scannability.

    Moreover, do not present the categories in a drop-down dialog. Multiple subjects explicitly stated that they had to scroll through the entire list to choose the category in which they expected to find a particular product. The problem with a drop-down quickly became clear, then: because it takes up only 50% of the available screen, getting an overview of the available categories became needlessly difficult (see Best Buy below).

    Because the gesture area is also only half the size, the subjects also had a much harder time accurately controlling the scrolling speed. Lastly, the drop-down interface element was confused with a filter selection by some subjects and not recognized as the main website category navigation.


    Do not follow the example of Best Buy, which does not have a category option in the main body of its home page content. Instead, a “three bars” icon takes the place of a category option in the page’s header. This not only requires all users to understand the meaning of the three bars icon, but also makes it impossible to get an overview of the store by scanning the home page. And, of course, using a drop-down to actually select a category is not ideal either.

    Perfect Fold Alignment

    Finally, do not design your website to have perfect alignment or white space exactly at the fold. This happens on GAP’s website, where it is easy to doubt whether the home page contains more than a search field and a few graphics (i.e. no category navigation), because these home page elements align precisely with the viewport fold (on an iPhone at least).


    One subject, a bit surprised, asked, “This is it? This is the entire page?” believing this was GAP’s entire home page. When elements are spaced with pixel-perfection alignment around the viewport fold, users are more likely to misinterpret the top part as being the entire home page (in this case, missing out on the category navigation below).

    To indicate more content, simply align the elements so that some are only partly viewable within the viewport on the most popular mobile devices.

    Therefore, when designing a scannable home page:

    • Put very few (if any) very visually stimulating graphics above the fold on the home page, and make sure the ones that are there have a clear eye path so that the user can quickly get an overview.
    • Try to ensure that the fold (on the most popular mobile devices) partially cuts off some content, to indicate more options below.
    • Display navigation options on the home page as a list (not in a drop-down).
    • If you have only one category navigation type (such as “product type” or “department,” and not also “brand” or “store”), then show the first level of the category hierarchy directly on the home page either in full or, if there are too many options, as a curated and collapsed list of the most popular choices.
    • Only display highlighted or featured products below the search field and the category navigation options.

    2. Be Sensitive To People’s Fear Of Losing Their Data

    Issue: Typing on mobile devices is clumsy, so users are constantly worried about losing their inputted data.

    “Argh, no! Do I have to start over? Now I’m getting angry. Doesn’t it have my shit already?,” a subject moaned, referring to his previously typed address and credit-card information, which suddenly disappeared. “Now I’m leaving. This isn’t a serious store.”

    Data persistence is not something to take lightly. Your users certainly don’t. Of course, the recommendation is simple: always persist the user’s data, which requires investing in solid technology, testing thoroughly, and storing inputted data temporarily on the user’s device (most mobile browsers support localStorage). In practice, of course, this is easier said than done, and numerous websites have failed miserably, to the great frustration of users.

    Because users have already suffered through many horrible experiences of lost data, they often exhibit extreme caution around certain types of elements and avoid certain interactions when possible. The following screenshot shows the types of actions and elements that particularly worry users. Either avoid these elements altogether or soothe users’ fear with the smart use of microcopy, icons and animations.

    During checkout, the subjects consistently opened links in a new window because they were afraid their data would be lost if they opened links in the current window.

    Subjects were almost always disturbed by unexpected page reloading (i.e. any page reloading that is not a direct consequence of clicking a link or button). In the image above, a subject selected a “Residence type,” which reloaded the page, causing the subject to immediately scroll up and down to ensure that none of their data was lost. We observed this type of unease with page reloading among subjects time and again throughout testing.

    Many subjects were scared by system dialogs and often assumed that they would lose data by clicking “OK,” even though few of them actually read the message. The subject in the test shown above wanted to go backwards in the process to pick another ticket but was met with this dialog, which he cancelled — assuming that he would have to re-enter everything if he wanted to select another ticket.

    A good number of the subjects believed that leaving the checkout process would destroy their data and so refused to go back and check for other products. The subject in the test above contemplated going back to find another bouquet of flowers, but decided against it because he did not want to re-enter all of his data. This happened despite many of the test websites actually remembering the users’ details, even if the users left the checkout process midway — the keyword, of course, being “many” websites, rather than “all.” Given this inconsistency, users have no way to know beforehand, so their only safe choice is to just assume the worst on all websites.

    During checkout, the “back” button was generally perceived by the subjects to be dangerous, and subjects used it during checkout only when they felt they were out of all other options. In many cases, this perception was justified: numerous websites did indeed fail to persist the user’s data when they used the “back” button. However, equally important is that process step links and other “back” links and buttons that were part of the website’s UI were generally considered by the subjects to be “safe.”

    Therefore, including either process steps or “back” links in the checkout is crucial so that users do not feel they have to gamble by using the browser’s “back” button and can instead use your website’s dedicated UI element(s) for the purpose. In the test shown above, the subject hunted up and down to find a link or button that would take him back to the previous step, but was unable to find one. Finally, he tried the browser’s “back” button.

    These were the most significant insights relating to users’ fear of lost input. In general, the subjects were vastly more pessimistic about websites on which they had once lost data. For example, clicking the keyboard’s “next” button cleared one subject’s input on a website, which made her consistently avoid that button throughout the rest of the checkout. As she said, “Here, I don’t dare click ‘Next’ anymore because I don’t want to start over again.” Not only that, the subject also became overly cautious when interacting with any fields on the website, fearing that even the slightest hiccup would destroy her data.

    A single bad experience set low expectations for the rest of the website. So, how do we avoid bad experiences in cases where we are unable to persist the user’s data due to technical limitations? In these instances, clearly warn the user that they are about to do something destructive.


    As the subject left the incomplete checkout, the website warned her that her data would be lost. “This is very good,” the subject remarked, “because if I did something wrong by accident, I would be extremely annoyed if they deleted everything. So, it’s good that they warn me like this if the data would otherwise be lost.”

    Persisting data is always the ideal, of course, but warning the user and giving them the option to back out before destroying their data is a good secondary solution, and it sure beats simply destroying the user’s data without warning; moreover, it gives the user a chance to cancel the destructive action. This type of fallback solution could be especially useful for less common navigation paths, where persistent data is too time-consuming to implement, considering how few users it affects.

    This could also entail something like persisting the user’s cart or checkout data when switching between the full website and mobile website. In these instances, it is acceptable to simply warn the user that they will lose their data if they proceed, and then give them the option to proceed (and lose their data) or stay (and keep their data).

    Data persistence is clearly a complex matter, especially when one considers the user’s expectations towards data persistence. We observed subjects creating accounts merely to ensure persistence, and witnessed data lost due to accidental clicks, and we watched with as much surprise as the subject when an entire form was remembered perfectly by autofill, turning potentially horrible data loss into a small moment of joy. Data persistence is tricky, but getting it right is crucial.

    3. Add A Primary Button At The Bottom Of Product Pages

    Issue: Users are likely to misinterpret cart buttons in the page’s footer if there is no “Add to Cart” button at the bottom of every product page.

    A wide range of the tested websites had multiple identical primary call-to-action (CTA) buttons on product pages (i.e. two “Add to Cart” buttons), one at either the top or middle of the product page and a second one at the bottom.


    On Best Buy, one subject read this product’s entire specification sheet and was in the mindset of “Yes, this is the product I want to purchase.” He saw the website’s shopping-cart icon at the bottom of the page (second image above) and clicked it, believing it was an “Add to Cart” button. Logically, he assumed the product would be added to his cart and so continued browsing for more products, only to notice much later in the shopping session that the website had “deleted” his cart’s contents (the TV was never added in the first place).


    The subject here on Amazon thought the shopping-cart icon was the button for adding the displayed product to her cart.

    It turned out that on the websites with only one CTA button on a product page, subjects often ran into severe problems even with adding a product to their cart — which, in some cases, ultimately led to abandonments. Cart icons in the page’s header or footer were often mistaken for an “Add to Cart” button.

    Both Best Buy and Amazon failed to make the primary buttons immediately obvious and generally available, which led subjects to start interpreting various icons on the page, including the cart icon, as shown in the two examples above. Subjects often scrolled to the bottom of a product’s page when looking for the “Add to Cart” button (a behavior confirmed in another study).


    This subject started looking for the “Add to cart” button by scrolling to the bottom of the page, then scrolling back to the top of the page, thinking she might have missed it, and finally scrolling down again patiently, until finding the “Add to bag” button in the middle of the page.

    To accommodate this behavior and reduce misinterpretation of any cart icons, add a second “Add to Cart” button to the bottom of all of your product pages. A second button there will also support a more natural interaction flow, as the user first reads the product description, then the specification sheet, then the reviews and so on, and then, at the end of the page, decides whether to buy or not. Only if the product page is extremely short (one to two mobile viewports tall) would a single button suffice.

    4. Be Very Careful With Animated Carousels

    IssueUsers fail to discover vital features that appear only in a carousel, and they have a hard time interacting with carousels themselves.

    Animated carousels caused interaction problems for half of the test’s subjects. The carousels simply changed too quickly for some subjects to both read and select an option.


    A subject was about to click the “Mega Sale” slide (left image), but the carousel animated to the next slide at the very same moment, forcing the subject to wait for that slide to reappear.

    In multiple instances, a subject found a carousel slide interesting and attempted to tap it. However, the carousel changed to the next slide at the very same moment, causing the wrong slide to load. Sometimes the subjects noted this, but sometimes they did not and left the landing page immediately because they did not find it relevant to what they were looking for.

    Interestingly, the “Prev” and “Next” buttons in the Toys “R” Us carousel were not used by a single subject during testing, despite these issues:


    The carousel changed the very second this subject tapped it, registering a click for “Bike Blast” instead of the “Mega Sale” she wanted. The subject never noticed and assumed that “Bike Blast” was the sale.

    Both of these interaction issues were also encountered (and still exist) in the early versions of carousels on full websites, but as carousels have become increasingly popular on e-commerce home pages over the last several of years, they have evolved, so most now stop animating when the user hovers over an option with the mouse.

    And most also have an indicator that enables the user to see how many slides a carousel has and, just as importantly, to jump to a particular slide (such as back to the one that piqued their interest but changed too quickly). These interaction issues cannot be easily solved on mobile because there is no hover state and much less screen real estate.


    On Toys “R” Us’ home page, the subjects pored over the menus to find a “Gift Guide” wizard but could not find one (image on left). It turns out there is a wizard but is accessible only via a particular slide in the rotating carousel at the top of the page.

    Perhaps an even more critical usability issue is that most test subjects simply ignored the carousel after quickly glancing at the first slide. Some waited and looked at two to three slides before focusing elsewhere. This proved critical on some websites, such as Toys “R” Us’, because the majority of subjects were desperately looking in the traditional navigation for certain features (such as the “Gift Finder”) that were accessible only via the carousel. Some subjects spoke at length about how the website really should have some sort of “gift guide,” ultimately abandoning the website because they could not find one.

    Users ignore animated carousels for multiple reasons. First, a carousel’s content might look like advertising, depending on how it is styled, greatly increasing the chance of banner blindness (a subgroup of subjects tended to focus much more closely on text-based navigation than on graphics-based navigation). Secondly, when using a large laptop or desktop monitor to browse a full website, the user is able to check out other options on the home page while still glancing at the carousel slides as they change.

    On mobile devices, however, the screen is so small that a carousel would take up a significant portion of the viewport, making it practically impossible to scan any navigation or category options while monitoring the carousel slides (one of them will always be partly or completely out of sight). Therefore, if users are to see all options in a carousel on a mobile device, they will have to watch the carousel for its full duration (like a video clip).

    Regardless of the cause(s), what is really important is that the vast majority of subjects ignored the animated carousels completely and, on the home page, focused instead on the category navigation and search features. For this reason, be very cautious about relying on carousels for important content, and never have it as the only path to a particular feature.

    5. Be Careful Of Showing Product Information Or Images On Separate Subpages

    Issue: Users have incredible difficulty understanding the scope of product subpages.

    On a mobile device, understanding the scope of the current page is vastly more difficult for users, due to the very small display. Mobile pages often lack the subtle yet vital page-scope cues that are present on full-size pages, such as a full set of breadcrumbs, an overview of the current page, and full URL paths viewable throughout the browsing session.

    This lack of scope on mobile makes having any kind of substeps or subpages that refer to a main page very risky, because the user would have to fully understand the scope of the current page in order to appreciate the difference between the subpage and main page.


    When users want to see larger versions of images of an Amazon product (left), they are taken to a subpage (middle). Our test subjects clearly noticed that they were still within a product’s particular scope (because of the large product image), but they did not understand where the rest of the product page went (right).

    This became immediately apparent when testing websites that offer a “larger view” option of their images, taking users to a separate product subpage, as seen on Amazon above. Because of the apparent lack of access to vital content, such as “Product Description,” “Product Specs” and “User Reviews” (which are available only on the main product page), the subjects who did not notice this change in scope assumed that such content simply did not exist for the given product and continued looking for other products with such information, discarding perfectly matching ones.


    Amazon also uses subpages to show full specification lists, causing the exact same issue, except that this time subjects were unable to locate something as vital as the “Add to Cart” button.

    On a mobile device, and especially on subpages, understanding the current scope is simply much more difficult. Instead, display your “larger views,” image galleries, detailed specification sheets and the like (i.e. all relevant content) directly on the product’s main page. You could also use progressive disclosure by collapsing each content section by default, to avoid overly long pages; but then be sure to have clear trigger indicators. A strategy such as this minimizes the need to display additional information and images on subpages and the resulting scope issues.

    Especially with image galleries, you also have the option of an overlay, as shown above on Foot Locker. With an overlay, the user can still see the product page beneath and have a simple way to get back to it.

    6. Be Thoughtful In The Design And Sequence Of Your Three Account-Selection Options

    IssueUsers had difficulty figuring out how to initiate “Guest Checkout” and understanding field relationships, selection options and buttons in the account-selection steps.

    On mobile, the user’s selection of a checkout type — “create an account,” “sign into account” or “guest checkout” — will be a separate step (unlike on full websites, where it could be integrated into the first step). More than half of the test subjects (60%) had serious trouble identifying, seeing and selecting the guest-checkout option at the account selection step during checkout.

    Multiple times, the misunderstandings led subjects to believe that registration was required, despite it being optional, and carried all of the downsides of forced account registration (including abandonments). Therefore, the design of your account-selection screen for mobile is just as important as having a guest-checkout option at all.

    Several different design schemes led to these serious misunderstandings, as the following screenshots illustrate.

    On Macy’s, subjects saw the account-selection step (above left) after selecting the cart. Some clicked “Express Checkout,” believing they would have a fast checkout (as a guest), only to get form-field validation errors for the two fields because “Express Checkout” requires a Macy’s account (above center). Some only discovered the “Checkout as a Guest” option further down the page (right), after getting this validation error, while others never noticed the guest-checkout option and registered for an account, believing it was required.

    On multiple websites (Amazon, Toys “R” Us, REI, GAP, Best Buy), subjects started to interact with the fields, such as by providing their email address (above). On REI, every single subject interacted with the email field before looking for, or figuring out that there was, a guest-checkout option.

    In most cases, the subjects spotted the error before submitting the form (typically upon reaching the password field and deducing that they were on an account sign-in or creation form). In such cases, not even detailed analysis of your Web statistics and error logs would reveal these issues because no validation error ever occurs.

    On Buy.com, things are even worse. The vast majority of subjects simply could not figure out the relationship between the four checkout methods (sign-in, create account, guest checkout and PayPal checkout), the two form fields, the three radio buttons and the two primary buttons. All tapped the “Checkout as a Guest” option after spending some time trying to understand the page.

    Then, the naming of the “Sign in Using Our Secure Server” button utterly confused subjects because they were trying to check out as a guest (and, therefore, actively opted not to sign into anything). This particular naming has been used by Amazon for years and has even been highlighted as a best practice to indicate a secure checkout, so how could it lead to such major misinterpretation?

    The reason is that it indicates the user will sign in, which makes sense only if they have an account or will create one, but not if they are checking out as a guest. (Amazon does not offer a guest-checkout option, so the wording makes sense in that context.) Given the button’s name, one subject assumed that the only other prominent button on the page, “Checkout with PayPal,” must be the one to pick to initiate the “Checkout as a guest” selection.

    Others finally clicked the oddly named button — but nothing seemed to happen. It turns out that inline text reading “Required” appeared next to the “Enter your eMail Address” label (seen above), but no one noticed it initially. The subjects typically waited for a little while just in case the website did not load, and then clicked again, at which point most realized that they needed to fill in more data. By this point, some, especially those who did not notice the validation error, concluded that they were not allowed to check out as a guest and proceeded to create an account instead.

    One explained his experience thusly, “Normally I would think ‘guest checkout’ would let me through without having to create an account. But here I have to fill in my mail, so I have no idea what that option is for, then. To be on the safe side, I’ll then pick the ‘No, I’m a new customer,’ because if I’m forced to create an account, I might as well just do it properly anyways.”

    Making the account-selection process clear is as important as offering a guest checkout option. Following two main design principles will help to prevent these serious problems:

    • Always place the guest-checkout option at the top, with its own button to proceed, so that the user does not need to fill in an email field in this step. (If needed, you can look up whether the user has an account in the next step, when you ask for their email address, to ensure that they have not selected the guest checkout just because it is the first option in the list.)
    • Collapse all of the fields and descriptions for all three options — “guest checkout,” “sign in” and “create an account” — bringing each option down to a single line, making it possible to get an overview in the viewport without having to scroll or expand. Dynamically expand them when tapped, revealing the fields and descriptions. This will also make clear which fields are related (and required) for each option.

    Below, we have created a simple mockup to illustrate how account selection can be clarified by combining these two principles:


    All three account-selection options are displayed in collapsed state (with guest checkout at the top), so that the user can instantly see all available options. The options can either expand inline (image on right) or redirect to the next step in the checkout process. Progressive disclosure also makes the relationship between an option and its fields much clearer.

    7. Disable Autocorrection When The Dictionary Is Weak

    IssuePoor autocorrection is frustrating when users notice it, and can be detrimental when they do not.

    Autocorrection usually works poorly for abbreviations, street names, email addresses and similar words that are not in the dictionary. This caused significant problems throughout testing and resulted in a great deal of erroneous data being submitted as subjects completed their purchases.


    When this subject typed in his street name, “westheimer,” the phone incorrectly autocorrected this to “weathermen” (left). However, the subject did not notice this, submitted the form and received a validation error (right).

    One of the major issues of autocorrection was that the subjects often failed to notice the correction (because they were often focused on what they were typing, instead of what they had typed). This is fine if the “correction” is correct, but it can be detrimental if it is wrong. For example, in multiple instances, a valid address was autocorrected to an invalid one and submitted because the subject failed to notice it.

    On websites without address validators, this resulted in wrong addresses being submitted, unless the subject was particularly attentive on the order review page. After all, the user’s address will often be replaced with something that looks very similar, although incorrect. In addition to the “weathermen” example, official address abbreviations, such as “Rd,” were autocorrected, to “Ed.”

    That being said, autocorrection did prove very helpful when it worked. So, don’t disable it in all fields. Use it discreetly, and disable it on fields for which autocorrection dictionaries are weak. This typically includes names of various sorts (street, city, user) and other identifiers (such as email address).

    You can disable autocorrection by adding an autocorrect attribute to the input tag and setting it to off, like so:

    
    <input type="text" autocorrect="off" />
    

    8. Make Fields Long Enough To Fully Display Common Data (And Put Labels Above Fields)

    IssueUsers cannot easily spot errors, let alone correct them, when the field is too short to display the entire inputted data.

    Due to the small size of mobile screens, form fields often get so short that users cannot self-validate before submitting their data, and users have a very difficult time correcting any validation errors because they cannot see the inputted data in its entirety.


    “I can’t see what I’ve typed. Argh. Then I’ll delete everything and retype it.” On REI, a validation error for an email field that was too short to be displayed in its entirety made it impossible for the subject to see what the actual error was. In trying to pan the inputted text, the subject accidentally enabled both the iOS text-selection tool and the text-replacement tool.

    Form fields that are too short presented problems for many subjects who tried to confirm the validity of their data before submitting it. They often made complaints such as, “I can’t see if the emails are the same when the email field isn’t long enough.” Some examples are seen below.


    On the left: Amazon’s email field is too short, despite the abundance of white space. In the middle: United’s credit-card field shows only 15 characters, even though most card numbers are 16 digits. On the right: Macy’s email fields are too short for users to verify whether the two addresses they’ve inputted match.

    Given how easy it is to make a typing mistake on a mobile device, fields that are not long enough to allow users to validate their data before submission are very harmful to the typing experience. Even worse, they make correcting any validation errors unnecessarily difficult.

    Note that in the case of Amazon and the earlier example from REI, the white space is sufficient to make the field much longer, while the other two examples have no additional space to make the fields longer because the labels are all left-aligned. For this very reason, labels should be placed above form fields to allow full use of the space and to display all of the user’s data (at a decent font size). Displaying labels to the left of the fields would be acceptable only when the device is in landscape mode (as explained in detail in “Mobile Form Usability: Place Labels Above the Field”).

    An adequate width for email and address lines is the full screen. Then, adjust the font size of the fields to allow for the full display of reasonably long data, such as first.lastname@my-company.com. (The character-length distribution of our own newsletter list shows that 96% of email addresses are 30 characters or fewer.)

    9. Enable Users To Verify The Inputted Day And Date

    IssueUsing text fields for dates requires unnecessary mental processing of the user and can cause serious selection errors.

    During testing, websites that had only a simple text field or drop-down dialog for date selection presented problems for 80% of the subjects.


    This subject was among the 80% who were unsure which date “this Friday” was. So, she decided to count the days on her hand, wanting to make sure she picked the right one.

    This happened with both Southwest (which uses drop-downs for the month and day) and United (which shows a text field for writing MM/DD/YYYY). On both of these websites, the following scenarios occurred:

    • A handful of subjects had to count the days on their hand (as explained above).
    • Half of the subjects went off-site and opened the phone’s native calendar app to double-check the date for their weekend trip (to confirm “this Friday”). In the instance seen above, this calendar verification goes completely awry because the subject checked the day of June 15th, instead of July 15th, and ended up purchasing a flight ticket for his “weekend” trip that left on a Sunday and returned on a Tuesday.

    • Lastly, a few struggled with typing and using the text-selection tool to enter the correct date on a website that uses a text field for date selection.

    By contrast, on the three test websites that provided a graphical interface for inputting dates in the form of a calendar view (namely, Enterprise, Avis and 1-800-Flowers, seen above), not a single one of these issues arose, and the subjects generally liked being able to verify the day and date they were selecting. This could potentially save customers from incorrectly counting or “verifying” the wrong weekday (as mentioned earlier) and thus booking the wrong date.

    While this is an annoyance on desktop as well (since the user would be no better equipped to spot the errors there), the severity and impact on the user’s experience is much greater in mobile when it comes to correcting the erroneous data, because panning and editing truncated data on a three- or four-inch touchscreen is much more cumbersome than using a mouse or keyboard arrows on a desktop. Furthermore, ordering tickets on the wrong day is much less likely on the desktop because the booking form and a separate calendar application can be displayed next to each other — whereas on mobile, only one can be viewed at a time.

    Therefore, always provide an interface that enables users to verify the day of their selected date. One option is to display a calendar interface in which the user explicitly selects the date they want. That would simplify the actual selection interface and, more importantly, gives users a chance to verify the day. If you already use a drop-down for date inputs and do not want to replace it, you could instead append the day after each date option (for example, “March 15 – Monday”); although that would require the month to be included in each drop-down day value or, in case a separate drop-down is used to select the month, you would need to dynamically update the day names depending on the currently selected month.

    10. Make The Hit Area For Each List Item Distinct

    IssueWith some lists, users simply have no idea where to tap in order to select an item.

    Can the entire “element” be tapped? Or only the product title? And what about the thumbnail? During testing, multiple issues arose as subjects were unsure of where to tap in order to select an item in a list. This was by far the worst on websites where list items were above the recommended half-screen height. In fact, one subject got completely stuck and was unable to complete her purchase.

    The problem was by no means limited to websites with list items that were too tall; it was just worse on those websites. The issue also extended to websites whose list items were normal in size but whose hit areas were unclear, which severely limited the subjects and even resulted in abandonments.


    It simply was not clear to subjects what can and cannot be clicked on this page. Note the very inconsistent link styles. Orange is sometimes used for the header, other times for a list item. Separators are sometimes used to set off list items, other times to set off elements of text. Some text is one shade of blue, which sometimes indicates a link, while other links are styled in a darker blue and underlined. Confused yet? The subjects were, too.


    Note how the subject was trying to click the “Lowest Fare” label, believing this was the button to choose the displayed flight. Besides the primary button being unclear, the list item is also very long. Combined, these two design choices are a surefire way to leave some users in doubt on how to even proceed.


    On the left: This subject did not know what to click in order to proceed on United’s website. Presumably, this was caused by the single result. With no options to compare and choose between, it was not clear to the subject what to select. On the right: Many subjects did not pick up on the ticket icon and its meaning on Fandango’s website. Instead, they assumed that the movie was playing only in theaters where a “Buy” button was shown (which was not the case).

    The images above show only some of the many instances where it was unclear to subjects what elements are clickable, what the differences are between the different hit areas and, most importantly, where to click in order to select an item in a list. The websites with the far fewest problems with hit areas embraced multiple of the following recommendations:

    • Make the entire element area clickable. In particular, the thumbnail, product header and price should be clickable and should lead to the product page.
    • Style the title as a link (using your primary style for text links).
    • Indicate the virtual space with an arrow or similar visual cue, showing that the entire list item will move the user to the next step in the process.
    • Consider separate “Buy Now” or select buttons for very long list items — i.e. when a list item could be easily mistaken as pieces of information, rather than a collective entity to be clicked.
    • Avoid multiple hit areas within the same visual element — in particular, links or buttons within a list item that lead to different pages.

    Designing M-Commerce Websites

    Aside from their practical use, these 10 recommendations have hopefully given you a glimpse of just how complex designing an m-commerce website really can be. It’s not simply a matter scaling and adding media queries; it’s an entirely new platform, and the balancing act is particularly difficult to get right due to the complex tasks involved, such as product finding and product comparison and multi-step processes such as checking out. In many ways, designing and optimizing an m-commerce website is much more difficult and often requires more “intelligent” website features than a traditional desktop e-commerce website. It comes as no surprise that IBM reports average m-commerce conversion rates that are roughly half of its desktop e-commerce conversion rates.

    In general, the more complex a mobile website’s features, the more likely the experience should be significantly different from the desktop experience. The greater the difference between the two, the stronger the argument for having a standalone mobile website. Of course, maintaining two versions of the same website comes with many issues, especially with maintenance (of content, code and design). A responsive design is a better solution in some cases, but it depends very much on the size and complexity of the website, as well as on your organization’s strengths and weaknesses. It’s a nuanced issue, with many gray areas and with good arguments both for and against having a standalone mobile website.

    If you can achieve this by designing for mobile first, then a responsive design could be truly great — not just in its maintainability, but also its user experience. Be clear, however, that if your existing website is complex, merely scaling it down to different devices won’t be enough to offer a great mobile experience. And if messing with the full website’s existing structure and content isn’t an option, then you might be forced to create a standalone mobile website in order to provide a decent experience — although maintaining content and code on the two separate platforms in parallel could turn out to be both expensive and messy.

    Thus, getting an m-commerce website right tends to be very resource-demanding, as you account for all of the nuances. But the opportunities are great. This is a new world, and it will take time before best practices stabilize. Spending time and money on a mediocre m-commerce website is wasteful. Yes, making the website great will require significant investment, but the potential payoff is high, too. M-commerce is a window of opportunity; it enables you to distinguish yourself from competitors and to position yourself well to grab a share of this market, which is expected to reach $86 billion by 2016.

    Note: Find out more about m-commerce usability guidelines in the (paid) report “M-Commerce Usability.”

    (al) (il)


    © Christian Holst for Smashing Magazine, 2013.

  3. Case Study: Typographic Design Patterns And Current Practices (2013 Edition)

      

    Good typography has always been a defining aspect of effective Web design, and this holds true especially for websites in which the emphasis is on presenting a large amount of content — specifically, articles, news and stories. Whether for a magazine or international newspaper, the designer of any website that distributes a lot of content has always had to consider typographic details as seriously and thoroughly as a print designer would.

    In 2009, we conducted a survey of then current typographic practices. Since then, responsive design techniques have clearly gained momentum and established their place in the landscape of CSS layout. With the advent of mobile, new modes of browsing websites and reading text have emerged.

    Online publications have had to reevaluate how their content is presented on mobile devices. Web typography is as rich, versatile and accessible as ever before. Yet new opportunities introduce new complexity; and with new implementation challenges, we are all spurred to reconsider our practices.

    Now, three years later, we’ve reviewed the original study and explored how Web typography has changed over these years. We spent countless hours between February and April of this year collecting new data and exploring common developments and trends in Web typography.

    How Did We Conduct The Study?

    We have compiled relevant data from over 50 well-respected websites to address these questions. For this study, we selected a wide variety of international newspapers, magazines and blogs, all of whose typographic choices should have been carefully and thoroughly weighed. We chose publications and organizations that have a very large readership (such as The Boston Globe and The Financial Times) as well as specialized magazines with smaller yet often more demanding readerships (such as A List Apart and UX Booth).

    These websites focus primarily on text-based content rather than on generic environments such as Instapaper and Readability. As such, they need to be highly legible in order to ensure that users continue visiting and reading on their websites. Because readability of content is (or rather should be) the main design goal of these publications, the techniques they follow could be considered good practices. However, the results presented in this study should be taken with a grain of salt.

    Issues We Were Interested In

    The questions asked in our first study nearly four year ago remain relevant but need to be complemented by questions about the challenges of mobile devices. How widely has responsive design been adopted by publications, if at all? Has there been any change in the typographic choices of big and small publications? How many weights of a large font family should we deliver to mobile devices? How large should the font size of body copy be? How should the font size change on a responsive website? Optimizing readability could require changing the font’s style, size and spacing according to the viewport’s width and height.

    The second article in this series will address the growing diversity of eBook readers and mobile apps whose purpose is to give users a pleasant, improved or enhanced reading experience — from desktop readers down to smartphone readers. We were curious about the specifics of design and typographic choices that make reading articles in these applications more pleasing than reading on the original websites.

    Note: For the sake of continuity, we have stayed close to the format of the original study from 2009. This article is meant to update the data, and hopefully detect new trends and reach new conclusions.

    Typography In Online Publications

    After carefully analyzing the style sheets in the publications in this study, we compiled a comprehensive spreadsheet of typographic points and collected the relevant data. You can view a spreadsheet of the raw data, which contains more data than was pertinent to this article.

    Not limiting ourselves to the questions in the original study, we will broach issues that have arisen since then as a result of responsive design techniques, and we’ll examine whether such techniques are being applied at all. This led us to the following questions:

    1. How popular are serif and sans-serif typefaces in body copy and headlines?
    2. Which fonts are used most frequently?
    3. What is the average font size (on narrow, mid-sized and large screens)?
    4. What is the average ratio of the font sizes of headlines to the font sizes of body copy?
    5. What is the average line height of body copy?
    6. What is the average ratio of line height to font size in body copy?
    7. What is the average ratio of line height to line length in body copy?
    8. What is the average amount of space between paragraphs?
    9. What is the average ratio of paragraph spacing to line height in body copy?
    10. How are links styled?
    11. How many characters per line are common in body copy?
    12. How often are links underlined?
    13. How often are font fallbacks used?
    14. How often are responsive design techniques implemented?
    15. Which ratios of display sizes are discernible?
    16. How do websites deal with the performance of Web fonts?

    To answer these questions, we collected more than 40 data points, all of which can be found in the aforementioned spreadsheet. We can extract several rules of thumb from this data. We wouldn’t recommend acting on the data from this study blindly; the statistical data, however, will no doubt yield useful insights.

    Popular Serif And Sans-Serif Fonts

    “Which typeface to use?” Obviously, this is one of the most important questions a designer has to answer when considering Web typography. The typeface will set the tone for the entire website, and a poor choice could send the wrong message or thwart the intended atmosphere. The argument for either serif or sans-serif hasn’t been won yet. Interestingly, looking back to the results of the 2009 study, sans-serif typefaces seemed to be more popular in body copy and headlines. The last four years have seen a tiny shift away from that.


    Serif and sans-serif are almost equally popular in headlines.

    The motivations of designers likely haven’t changed much. Serif fonts apparently stand out in headlines, but arguments have been made for serifs’ ability to guide the reader and for its readable structure in body copy as well. Still, contrasting a serif body with a sans-serif headline or vice versa can improve the overall visual appeal and readability of a website.

    The data suggests that serifs have gained in popularity in recent years, leading almost to a reversal in common usage in the last four years, at least where body copy is concerned.


    Serifs have strongly gained in popularity in body copy.

    • Half of the websites analyzed use serifs in their headlines, the other half sans-serifs. The two most popular typefaces are Georgia — used on such websites as The Guardian and the Financial Times — and Arial — found on Zeit.de and the BBC’s website.
    • Only 37% use a sans-serif typeface for body copy.
    • The most popular serif typefaces for headlines are Georgia (14%) and Chaparral Pro (6%).
    • The most popular serif typefaces for body copy are Georgia (20%) and Chaparral Pro (4%).
    • The most popular sans-serif typefaces for headlines are Arial (10%) and Freight Sans Pro (4%).
    • The most popular sans-serif typefaces for body copy are Arial (14%) and Helvetica (6%).
    • However, 66% of headline typefaces and 39% of body copy typefaces are found in only one instance.

    So, in summary we can state that nearly two thirds of the websites analyzed use serifs for body copy, and Georgia and Arial are still the most common primary typefaces. However, our most surprising find is that a majority of websites use non-standard fonts as their primary typeface — 39% of body copy and 66% of headlines. This development is truly interesting, because it shows that typography has become an important element in establishing brand identity and character. These numbers indicate growing typographic diversity on the Web — which we should probably expect anyway.


    A majority of websites use non-standard fonts as their primary typeface.

    The growth of “bulletproof” font-delivery services such as Typekit and Fontdeck likely explains the increasing variety of primary typefaces. Fallback typefaces are predominantly standard core Web fonts. Times, Times New Roman, Georgia, Helvetica and Arial are most often used in CSS font stacks. Mobile platform fonts such as Droid Sans, Palatino and Cambria are almost never used.

    Ironically, a consequence of the resurgence in serif typefaces is that Times and Times New Roman, which had almost been written off as too old-fashioned in the last study, have made kind of a comeback as the two most popular fallbacks. Roughly 11% of headline and body copy fallbacks have Times, and another 11% have Times New Roman.

    There is much literature on typography in Web design, most of which discusses the applications of serif or sans-serif typefaces. Increasingly, the argument for better readability combined with artistic value supports a judicious use of both styles. Douglas Bonneville discusses the benefits and best practices of combining serifs and sans-serifs, and Simon Pascal Klein discusses the intricacies of font families and makes further typographic considerations in his article “Achieving Good Legibility and Readability on the Web.”


    The Great Discontent combines both the Stratum and Meta Serif Web Pro fonts to generate a dynamic yet respectable feel.

    Compared to the previous study’s results, Verdana and Lucida Grande are the big losers. Verdana is used only twice as a primary font, and neither is used more than once as a fallback font. Chaparral Pro and Helvetica have risen in prominence. The increasing diversity and individuality in design is due to both the increased use of font foundries and the wider range of Web fonts.

    One discovery of the previous study, that “alternative” fonts are more common among headline typefaces, is still proving accurate. No doubt, the general belief that experimentation is best applied to small details still stands. The look and feel of a page can be adjusted just enough by changes to the font family of headings, rather than by drastic changes to body copy. However, the overall use of alternative fonts for body copy has increased dramatically, creating a much richer and more diverse typographic landscape on the Web.

    Light Or Dark Background?

    The previous study concluded that a large majority of websites favored dark on light color schemes. Not much has changed, although the websites surveyed this time are more varied in their light background tones.


    An Event Apart demonstrates the readability of a subdued color scheme.

    Several websites have a less aggressive contrast of an off-white or even beige background with dark-gray text. The off-white is often chosen to lower contrast. The designers in this case have clearly opted for a comfortable, lengthy reading experience.

    Black text on a white background is a common pattern for body copy. The contrast is easy on the eyes and is, at least among these websites, the status quo.

    Average Font Size For Headlines

    Generally, the font size of headlines is chosen according to the typeface of the body copy. Still, it’s interesting to see what common ranges designers prefer for body copy and headlines. In this study, the headlines for large display sizes average at roughly 38 pixels. Of course, we made sure that the text always displayed at the actual size, without any zoom.


    The most popular sizes range from 20 to 32 pixels.

    You can easily notice the increase in font size since the last study. Not only did the average increase by more than 10 pixels (!), but the range of headline sizes starts further up, at 20 pixels, and tops out at an impressive 212 pixels in the case of The Great Discontent. This publication is an exception, with its magazine-like headlines and smaller font sizes for headings.


    We’re going further up. The Great Discontent shows an impressive 212 pixels font size.

    Average Font Size For Body Copy

    With readability as the determining criterion, the average pixel size of body copy has increased in four years as well. Back then, most of the websites were between 12 and 14 pixels in font size. Now, 14 pixels is as popular as 16 pixels; each is used on 13 websites.


    14 pixels is also The Verge’s font size. While some websites offset the first paragraph of an article with a larger font size, many, like The Verge, follow a uniform size.

    Ratio Of Headline to Body Font Size

    We’ve updated our rule of thumb based on the current average ratio between headline and body font size. Don’t follow this rule blindly; rather, just keep it in mind as you make decisions in your projects.

    Headline ÷ Body Copy = 2.5

    According to our study, on average, the ratio between the headline and the body copy is around 2.5. The traditional scale (6, 7, 8, 9, 10, 11, 12, 14, 16, 18, 21, 24, 36, 48, 60, 72) and the Fibonacci sequence (16, 24, 40, 64, 104) are still relevant, of course, and represent a more naturalistic approach. The golden ratio (1.618) might also yield an organic effect, too.

    Optimal Line Height For Body Copy

    Leading (or line-height in CSS) will always depend on your font size and measure (or line length). But in general, the longer the measure, the longer the leading should be. Therefore, presenting a chart of the most popular leading values in pixel units wouldn’t make sense here. More appropriate for you would be to use a relative unit, such as an em or percentage value, that determines the ratio between leading and measure and between leading and font size.

    This latest study reveals the following:

    • line height (pixels) ÷ body copy font size (pixels) = 1.46
      Classic typography books recommend 1.5, a value backed up by this and our last study. Very few websites use anything less than that. The number of websites that go above 1.48 decreases as you get further from this value.
    • line length (pixels) ÷ line height (pixels) = 24.9
      The average line length (570 pixels, excluding margins and padding) has grown comparatively less than font size and line height have since 2009 (the latter averaging 22.9 pixels). The average line lengthened by approximatively 5% (from 538,64 pixels in 2009), while the average line height has increased from 12 pixels in 2009 to 13 pixels in 2013.
    • space between paragraphs (pixels) ÷ line height (pixels) = 1.39
      In the first study, it turned out that paragraph spacing (i.e. the space between the last line of one paragraph and the first line of the next) rarely equaled the leading (which would be the main characteristic of a perfect vertical rhythm). According to our results, paragraph spacing is around 1.39 × the paragraph leading. Paragraphs are more clearly delineated with this increased ratio, thus increasing readability.

    Multiplying the value of your body’s font size by 1.46 would give you the optimal line height, which you could then adapt to your font style. Multiplying this new value by 24.9 should give you the optimal line length. Note that the layout would also need gutters, margins and padding to let the body copy breathe.

    Characters Per Line

    As explained by Robert Bringhurst, the classic rules of Web typography dictate that the optimal number of characters per line is 55 to 75. Our data shows that at their actual size (i.e. with no zoom and at the default font size), most websites average 83.9 characters per line at a widescreen resolution (in our case, a browser width of 1100 pixels).

    While this average fluctuates quite significantly when the browser is at various other widths — between 83 and 86 characters per line at display widths of 700, 950 and 1600 pixels — only in smaller views of 500 pixels this average comes close to the classic rule. At that width, the average lies around 77 characters per line.

    This is most likely the result of an attempt among designers to balance the font size with the amount of text displayed on narrow screens. With more characters displayed per line, the font size would have to become small, making the reading experience a bit more difficult on the eyes.

    The highest number is, of course, much higher, but in general most designers stay in the range of 75 to 90 characters. In the most extreme cases, SB Nation has 55 characters per line, and Polygon averages 118 for the introductory paragraph. A more exact average could be derived by averaging several lines. But such an in-depth analysis probably would not vary greatly from the average that we calculated here. Still, the discrepancy between the number of characters at different widths is peculiar.


    Polygon displays more characters per line in the introductory paragraph than in the rest of the article. However, the font size of that paragraph is larger as well.

    Web Typography And Responsive Design

    A burning issue we wanted to explore was the impact of of responsive design in Web typography today. The results were surprising: 22 out of 52 (i.e. 42%) of the websites we analyzed show (minor or major) changes when the browser size changes. Considering that responsive design has been around for two years, that number is quite impressive. We calculated the number of characters per line, the body font size and the headline font size at five browser widths (and experimented with the height as well): 500, 700, 950, 1100 and 1600 pixels. The font sizes for those three metrics do not differ greatly across the screen sizes — except at the 500-pixel view.

    Unexpected, though, were the visual changes that occurred as we resized the browser. Changes in layout, image scaling, content and font size were evident to varying degrees on 22 websites. The changes are as minimal as images being scaled down to suit the display width. In some cases, however, the websites display other minor and expected changes. At the 500-pixel view, for example, the menu is often replaced by an icon; design components are moved from a multi-column layout to a single column; and both images and fonts are scaled.

    No sign of responsive design was evident on 30 websites, including major publications such as The Financial Times and The Economist. At least some, if not all, of these websites seem to opt for a separate mobile website or application. The Financial Times immediately invites mobile visitors to use its FT app. At the moment, large online publications seem to prefer to invest in an app than in responsive design. If this trend continues, then the question becomes, how much will users be annoyed by being prompted to download an app for every single publication they’re interested in.

    Despite this, we were happy to find that the layouts of the large majority of websites do not break when being zoomed in.

    Some Numbers on the Implementation of Responsive Design

    42% of websites implement responsive design changes, including for layout, image scale, content and font size.

    At a display width of 500 pixels:

    • Average line height: 28 pixels
    • Average font size of body: 15 pixels
    • Average number of characters per line: 77

    At a display width of 700 pixels:

    • Average font size of headlines: 36 pixels
    • Average font size of body: 15.6 pixels
    • Average number of characters per line: 82.7

    At a display width of 950 pixels:

    • Average font size of headlines: 37.9 pixels
    • Average font size of body: 16.1 pixels
    • Average number of characters per line: 84.8

    At a display width of 1600 pixels:

    • Average font size of headlines: 40.7 pixels
    • Average font size of body: 16.2 pixels
    • Average number of characters per line: 86.8

    These averages might be somewhat skewed because of the mixture of responsive and non-responsive websites. But they show how little the body font size and characters per line change over varying widths. The only exception is the 500-pixel width, which have a lower number of characters per line.

    Performance Considerations

    While embedded fonts are slowly becoming a de facto standard in Web design, they also introduce overhead in performance because, well, they have to be loaded. Chris Coyier recently discussed the idea of loading Web fonts only on large screens to avoid the performance hit. You could also load Web fonts into AppCache or LocalStorage first and show them on subsequent page loads.

    Moreover, you could use Google’s WebFont Loader to ensure that the content is displayed in fallback fonts even before the Web fonts have loaded, and then switch to the Web fonts once they have completely loaded (this is what we’re implementing in this very moment).

    Our study shows that Web fonts are indeed a heavy bottleneck in performance, with 5.7 font files being loaded on average, totalling an average of 133.5 KB of extra bandwidth. In cases such as a page being loaded on a slow mobile connection, the user would initially see no text other than the underlining of links (apparently due to the use of the border-bottom property). Only once the fonts have loaded would the text be visible — and even then, elements would appear one by one (headings, then subheadings, then body copy). We can avoid this suboptimal experience by properly adjusting the CSS font stack, as Richard Rutter explains in his talk “Responsive Web Fonts” (slidedeck).

    Other Findings

    • 45% of websites underline the links in body copy. The others do so only on hover or not at all.
    • 71% of websites highlight links with color. The rest do not or only on hover.
    • 99% of websites left-align text.
    • No website uses hyphenation.
    • 84% of websites use the same fonts in the print and standard style sheets.
    • The loading weight of home pages averages around 1.346 MB. Article pages are marginally less, at around 1.146 MB.
    • The websites average 119 HTTP requests!

    Conclusion

    This study has revealed a set of common practices in Web typography. These results should not be interpreted as law. They should not be interpreted as “best” practices; rather, just as rough guidelines that we encountered in current Web design.

    For example, the performance hit introduced by Web fonts and the (huge) number of HTTP requests should be reduced as far as it’s possible, while the content-out approach in responsive design would dictate how the font size would need to adjust depending on the settings in which it’s used. These findings are no doubt just a snapshot of current trends and may very well be outdated in a year’s time.

    • Serif fonts are more popular than sans-serifs for both headlines and body copy. There is, however, a trend to mix sans-serifs and serifs to contrasting effect.
    • The most common fonts for headlines are Georgia, Arial and Chaparral Pro. But the majority of websites are individualized and use less common fonts.
    • The most common fonts for body copy are Georgia, Arial and Helvetica. But, again, the majority of websites are individualized and use less common fonts.
    • The most popular font size for headlines is between 29 and 32 pixels.
    • The most popular font size for body copy is between 14 and 16 pixels.
    • headline font size ÷ body copy font size = 2.4
    • line height (pixels) ÷ body copy font size (pixels) = 1.47
    • line length (pixels) ÷ line height (pixels) = 24.8
    • space between paragraphs (pixels) ÷ line height (pixels) = 1.43
    • The optimal number of characters per line is between 55 and 75, but 75 to 90 is more popular.
    • Body text is left-aligned. Hyphenation is not used at line endings. And links are underlined and/or highlighted with bold or color, sometimes only on hover.
    • Mobile devices are mostly adapted to via responsive design, although some publications opt for a dedicated app.

    The decision of whether to modify any typographic element always lies with the designer. Most of the results shown in these websites are likely the outcome of much trial and error. When designing a new website, you might want to stay close to these parameters, but with adjustments to suit your layout. Feel free to review the study’s spreadsheet for the raw data.

    As we mentioned at the beginning, the second article in this series will deal with the intricacies of eBook readers and mobile apps. We don’t necessarily expect very different results. However, apps do offer more interactivity to the user. It will be interesting to see how much developers take advantage of the range of possibilities in mobile apps. Because there is not yet an inordinate number of readers on the market, we’ll accumulate data on as many readers as possible.

    More Studies On Smashing Magazine?

    Interested in more studies? Let us know what you’re interested in, and we’ll see what we can do!

    What kind of studies would you like to see on Smashing Magazine?

    (al)


    © Jan Constantin for Smashing Magazine, 2013.

  4. A Beginner's Guide: Migrating A Website To WordPress Is Easier Than You Think

      

    Now powering over 17% of the Web, WordPress is increasingly becoming the content management system (CMS) of choice for the average user. But what about websites built with an outdated CMS or without a CMS at all? Does moving to WordPress mean starting over and losing all the time, energy and money put into the current website? Nope!

    Migrating a website (including the design) over to WordPress is actually easier than you might think. In this guide, we’ll outline the migration process and work through the steps with a sample project. We’ll also cover some of the challenges you might encounter and review the solutions.

    About This Guide

    Before we get to work, let’s establish some context. First, this guide was written primarily with beginners in mind and will be most helpful for basic websites. Some of you will likely encounter advanced aspects of WordPress migration, but they are beyond the scope of this guide. If you’re tackling an advanced migration and get stuck, feel free to share your difficulty in the comments below.

    Objectives

    The objective of this guide is to help you with the following:

    • Plan an effective migration to WordPress.
    • Walk through the technical steps involved in migrating.
    • Get ideas and resources to solve common migration challenges.

    Assumptions

    I assume you have basic familiarity with WordPress. Previous development experience with WordPress would be helpful, but not necessary. I also assume you have an existing website and design that you want to migrate to WordPress.

    Basic Steps

    Here are the basic steps that I recommend you follow for a typical WordPress migration:

    1. Evaluate website.
      Work carefully through the pages on your existing website, identifying all of the types of content (standard pages, photo galleries, resource pages, etc.) and noting any areas that need special attention.
    2. Set up environment.
      Set up WordPress and get ready to import.
    3. Import content.
      Bring over and organize your content, whether via an importing tool, manual entry (for a small amount, when no tool is available) or a custom importing process.
    4. Migrate design.
      Incorporate your existing design into a custom WordPress theme.
    5. Review website, go live.
      Carefully review the import, making adjustments where needed, set up any URL redirects, and then go live.

    With this outline in mind, let’s work through each step in detail.

    Start With A Plan

    The key to a successful migration is to carefully evaluate your current website. You need to figure out how to import and structure the content in WordPress before carrying over the design.

    While the principles are the same across migration projects, the details often vary. So, below are two lists of questions to ask as you work out a plan.

    Imported Content

    • How much content needs to be imported (number of pages, number of images, etc.)?
    • Is the volume low enough to be imported manually, or do you need a tool?
    • If you need a tool, does one already exist?
    • Can the content be categorized into the standard “posts” and “pages,” or does it call for custom post types?
    • Does extra content need to be stored for certain pages (custom fields, taxonomies, etc.)?
    • Will the URL structure change? If so, will the old URLs need to be redirected?

    Existing Functionality

    • Does the website integrate any third-party services (data collection, reservations, etc.)?
    • Do any forms need to be migrated (contact forms, application forms, etc.)?
    • Is access to any content restricted (such as members-only content)?
    • Does the website sell products (digital or physical)?
    • Do any administrative tools need to be carried over (such as custom CMS functionality)?

    A Working Example

    My brother, Joshua Wold, has volunteered a website to serve as an example; it’s for a side project of his in which he sells posters and postcards of a Vegan Food Pyramid. He built the website in plain HTML, with some basic PHP includes for the header and footer. Below is a screencast of me evaluating the website to give you a sense of how the process will work. Enjoy!

    Set Up WordPress

    Before importing the content, we need to get WordPress ready to go. If you’re just experimenting or if you prefer offline development, start with a local installation of WordPress. Otherwise, the next step is to install WordPress with your current hosting provider; or you could use the migration process as a great opportunity to move to a new host.

    Once WordPress is up and running, you’re ready for action!

    For our example, we’ve installed WordPress with the same host, setting it up in a /wp directory for the duration of the migration process.

    Settings and Plugins

    With WordPress installed, we’ll make a few minor adjustments:

    • Update permalinks.
      Go to Settings → Permalinks to make changes. In most cases, I’ll switch to “postname”-style permalinks.
    • Update users.
      I create an admin-level account for myself and any admin or editor accounts that are needed for clients and collaborators. I also remove the default “admin” user name if it exists (a basic but wise step for WordPress security).

    Depending on the needs of the project, we might have to preinstall plugins. Here are the major categories of plugins:

    • Form management
      Migrating a form “as is” is usually a mess; simply recreating it using a forms plugin is usually easier. My current favorite is Gravity Forms ($39+ per license). Other options are Formidable (with free and pro versions) and Contact Form 7 (entirely free).
    • SEO management
      Search engine optimization (SEO) is a touchy subject. My philosophy is to build content for people, not for search engines. That being said, there is a common-sense approach to SEO that is solidly supported by the WordPress plugin ecosystem. And if your old website includes custom meta descriptions, giving them a new home during the importing process is important. I recommend WordPress SEO (free).
    • Multiple languages
      If your old website supports multiple languages, WordPress has you covered. My plugin of choice is WPML ($79 per license, free for non-profits). Another option is qTranslate (free).
    • Security
      WordPress security is a topic near and dear to me. The increasing popularity of WordPress has made it a target for security attacks. WordPress itself is rarely the problem; a poorly secured hosting environment or an outdated or poorly developed plugin usually is. I use managed WordPress hosting for the majority of my projects, which offers a good foundation for solid WordPress security. Options include WPEngine, ZippyKid, Pagely and Synthesis. In addition to managed hosting (and especially if you opt for a non-managed host), consider installing a security plugin, such as Better WP Security (free) or Wordfence (also free). Last but not least, review the “Hardening WordPress” guide in the Codex.
    • Backups
      If you opt for managed hosting, backups are usually included (make sure, though). If you’re managing backups yourself or you want an extra layer of data protection, great options are available, including VaultPress ($15+ a month), CodeGuard ($5+ a month), BackupBuddy ($75+ per license) and BackWPup (free).

    Import Content

    With WordPress up and running, it’s time to bring over all of your content.

    If your old website has a CMS, an importing tool might be available. Start by viewing the list of content-importing scripts in the Codex. If there’s a match, great! Follow the instructions and get to work. If all goes well, you’ll have migrated the content over without any trouble.

    If your old CMS is not in the list or you don’t have a CMS at all and you’ve got fewer than 100 pages, then manual migration is probably the way to go. Copy and paste the contents, noting the old URLs as you go (tracking the migration in a spreadsheet is a good idea).

    If you’ve got a custom CMS or a database of records without an importing tool and a high volume of content, then you might want to bring in a specialist to move the content over before continuing. The higher the volume of content, the higher the chance of human error and the more important automating it becomes.

    For our project, I’ve migrated the content manually and replaced the existing navigation with a WordPress menu. You can watch the process in this next screencast:

    Bring Over The Design

    With our content in WordPress, it’s time to bring over the design. Incidentally, if you’re considering a new design, then now is a great time to look at the many excellent WordPress themes out there, both in the official repository and in third-party marketplaces such as ThemeForest and Creative Market. For our purpose, I’ll assume that you’re happy with your design.

    Evaluating A Design

    Evaluate the source code of a prospective design as best you can before tackling the migration. If the code is table-based or more complex than you’re comfortable with, then migrating the design might not be worth the effort. While anything is possible (I’ve migrated some complex table-based designs in my time), not everything is practical.

    Working With Source Code

    In my experience, the easiest way to migrate is to work directly with the source code in the browser. While having access to the original hosting environment can be helpful (especially when working with a lot of images and downloadable files), the ways that websites are built vary so widely that you’ll often have to reverse-engineer the original architecture in order to derive anything useful.

    Going directly to the source code in your browser of choice will save a lot of time and, barring any important “behind the scenes” functionality, give you everything you need. Google Chrome is currently my browser of choice, and I’ve pulled our source-code samples directly from the browser. (In Chrome, go to Menu → Tools → View Source, or just right-click to bring up the contextual menu.)

    Create A Custom Theme

    If you’re new to them, learn about using themes in the Codex. For the migration process, you can either build a new WordPress theme from the ground up or modify an existing theme to meet your needs. I recommend the latter.

    Most of my migration projects have started with the latest version of WordPress’ default theme (currently Twenty Twelve). Recently, I stripped down the default theme to create my own migration starter theme, which I’ll use in our example and which you’re welcome to use yourself. (Feel free to suggest improvements!) Let’s get to work.

    Download a copy (ZIP) of the migration starter theme or follow along in your own theme of choice as we work through the relevant theme files.

    1. Style Sheet

    Our first step is to bring over the styles from the old website. In most cases, this is as simple as searching the source code for references to .css and then copying and pasting the contents from those style sheet(s) into our own style.css. Let’s get to it.

    1. Open up style.css.
    2. Replace the details of the theme (“Name,” “URI,” “Description,” etc.) with your own.
    3. Paste in the styles from the old website.

    A Note About Images

    As you migrate the style sheet(s), search for and update any references to images. In general, I like to keep all images in an /images/ folder within the theme’s directory. More often than not, changing the locations of images referenced in the original CSS is necessary, and I make sure to update all references in the style sheet and templates accordingly.

    2. Header

    The next step is to create the header for our new theme. Our objective here is to merge the structure of the current code base with WordPress’ templates. Here’s what we’re going to do:

    • Replicate the HTML structure of the old website.
    • Replace the static menu with a WordPress-powered menu.
    • Use WordPress’ title tag and leave the wp_head hook in place.
    • Merge any other relevant tags from the old header.

    Let’s get into the code!

    Original HTML

    
    <!DOCTYPE HTML>
    <html>
    <head>
    <title>Vegan Food Pyramid posters, postcards and wallpapers</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="google-site-verification" content="PO3bWDpUEh4O6XXwnmfyfxrKRDf8JsRrNIcGdzv3POs" />
    <link rel="stylesheet" type="text/css" href="/style.css" media="screen" />
    <link rel="shortcut icon" href="http://www.veganfoodpyramid.com/favicon.ico?v=2" />
    <script type="text/javascript" src="//use.typekit.net/tty6xpj.js"></script>
    <script type="text/javascript">try{Typekit.load();}catch(e){}</script>
    
    </head>
    <body>
    <a href="http://veganfoodpyramid.com"><h1 id="logo">Vegan Food Pyramid</h1></a>
    <ul class="menu">
       <li><a class="active" href="http://veganfoodpyramid.com">Products</a></li>
       <li><a href="http://veganfoodpyramid.com/wallpaper.php">Wallpaper</a></li>
       <li><a href="http://veganfoodpyramid.com/about.php">About</a></li> 
       <li><a href="http://veganfoodpyramid.com/contact.php">Contact</a></li>
    </ul>
    

    Merged Header (header.php)

    
    <!DOCTYPE html>
    <html>
    <head>
       <title><?php wp_title( '|', true, 'right' ); ?></title>
       <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
       <meta name="google-site-verification" content="PO3bWDpUEh4O6XXwnmfyfxrKRDf8JsRrNIcGdzv3POs" />
       <link rel="shortcut icon" href="http://www.veganfoodpyramid.com/favicon.ico?v=2" />
       <script type="text/javascript" src="//use.typekit.net/tty6xpj.js"></script>
       <script type="text/javascript">try{Typekit.load();}catch(e){}</script>
       <?php wp_head(); ?>
    </head>
    
    <body <?php body_class(); ?>>
    
       <header>
          <a href="http://veganfoodpyramid.com"><h1 id="logo">Vegan Food Pyramid</h1></a>
          <?php wp_nav_menu( array( 
                'theme_location' => 'primary',
                'container' => false,
                'menu_class' => 'menu'
          ) ); ?>
       </header>
    

    Explanation

    One of the challenges of migration is deciding whether to improve code as you go along. Our project has a few areas that could be improved, but Joshua and I agreed to leave them as is. Most of you will be tackling the migration of a design that hasn’t been coded to current best practices (although, in fairness to the original coder, they may have been best practices at the time).

    If time and opportunity allow, I encourage you to improve on the code. Otherwise, take comfort in the fact that, with the website now on WordPress, improvements will be a whole lot easier down the road.

    Let’s work through the changes we’ve made!

    • Doctype
      Make sure to carry over the same doctype. In this case, the original HTML already has an HTML5 doctype (a relatively rare occurrence on old websites). Using a modern doctype in a code base written for an older specification (such as XHTML or HTML4) could break the layout (especially in old browsers).
    • Meta tags
      I usually bring over the majority of meta tags as is, replacing them in WordPress. The exception in our case is the reference to the style sheet, which is being inserted automatically via wp_enqueue_style in the functions.php file.
    • Scripts
      Scripts can be tricky. If a script belongs on every page (such as a tracking script or font script), then putting it directly in the header (or footer) file is fine. If it needs to appear only on certain pages, then a conditional tag will do the trick. As a best practice, register all scripts and add them to the header (or footer) via wp_enqueue_script. If you’re up for the challenge, I recommend doing it this way. (Check out a tutorial on enqueuing TypeKit the right way.)
    • wp_head
      Leave <?php wp_head(); ?> at the bottom of the </head> tag in the merged header file. WordPress uses wp_head, among other things, to enqueue scripts and style sheets that are referenced in the theme (usually in functions.php) and in plugins that you’ve installed. Without wp_head in place, most front-end plugins won’t work.
    • body_class
      Notice our use of the <?php body_class(); ?> tag. WordPress uses this to provide a series of helpful classes to the <body> tag depending on the page being viewed. In our example, the <body> classes weren’t being used. Yours might have unique IDs or classes on each page, in which case you can create a custom function using conditional tags to add the appropriate classes to the corresponding pages. Have a look at the Codex for some examples.
    • WordPress menus
      Switching to a WordPress-powered menu is one of the more complex tasks in most basic migrations. It will be fairly straightforward for us. We have a menu with simple markup that uses an active class (generated via PHP) to indicate which page the visitor is viewing. The wp_nav_menu function is highly flexible and offers built-in functionality to handle the current state of an element in the menu. I’ve updated the references in the style sheet to the active class and changed them to use the equivalent generated by wp_nav_menu, which is current-menu-item. Watch the screencast on importing content to see how I’ve set up the menu for our example.

    And that’s a wrap! Let’s move on to the next piece.

    3. Footer

    The footer is usually the most uneventful template in the migration process. As with the header, our objective is to merge the relevant parts of the original source code. Let’s get to it!

    Original HTML

    
    <div id="footer"><p>© 2013 VeganFoodPyramid.com</p></div>
    
    <script type="text/javascript">
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
    </script>
    <script type="text/javascript">
    try {
    var pageTracker = _gat._getTracker("UA-6992755-1");
    pageTracker._trackPageview();
    } catch(err) {}</script>
    
    </body>
    </html>
    

    Merged Footer (footer.php)

    
    <div id="footer"><p>© <?php echo date('Y'); ?> VeganFoodPyramid.com</p></div>
    
    <script type="text/javascript">
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
    </script>
    <script type="text/javascript">
    try {
    var pageTracker = _gat._getTracker("UA-6992755-1");
    pageTracker._trackPageview();
    } catch(err) {}</script>
    
    <?php wp_footer(); ?>
    
    </body>
    </html>
    

    Explanation

    Some footers are hard to migrate (such as ones with complex menus and widgets), but most are simple. In this case, we’ve merged the HTML with our footer template, making sure to preserve our reference to the wp_footer hook. We’ve also changed the date reference to use PHP, ensuring that it updates with each year.

    4. Home Page

    One of the challenges of a migration is that there are so many different ways to get the job done. The home page is a good illustration of this because it tends to be the most different from the rest of the website. Adopting the simplest method is usually best. I’ve opted to put all of the home page’s content directly in the template. Changes will be rare and can easily be made by editing the template.

    Let’s look at the code, excluding the header and footer, which we’ve already covered.

    Original HTML

    
    <div id="content">
    
    <div id="poster">
    <a href="http://veganfoodpyramid.com/images/Vegan-Food-Pyramid-New.jpg"><img class="product-img" src="http://veganfoodpyramid.com/images/Vegan-Food-Pyramid-New.jpg" /></a>
    <div class="description">
    <h2>Poster</h2>
    <p>A 30×20-inch poster illustrating over 125 vegan food items as an alternative to the traditional food pyramid. This poster will catch people’s attention and serve as a suggestion for food ideas.</p>
    <h3>$30 each</h3>
    <p>Includes free shipping worldwide</p>
    <a class="button" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2FKQT879CXYYG">Buy</a>
    </div>
    </div>
    
    <div id="postcard">
    <a href="http://veganfoodpyramid.com/images/Vegan-Food-Pyramid-New.jpg"><img class="product-img" src="http://veganfoodpyramid.com/images/postcard-splash.jpg" alt="Postcard Splash" /></a>
    <div class="description">
    <h2>Postcards</h2>
    <p>Beautiful 4×6 postcards that can be mailed and shared with friends and family. Hand them out at events. Post them on walls. Share the vegan love!</p>
    <h3>$50 for 50</h3>
    <p>Includes free shipping worldwide</p>
    <a class="button" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=EN387WHNSSFMW">Buy</a>
    </div>
    </div>
    
    </div> <!-- end content -->
    

    Merged Home Page (/page-templates/front-page.php)

    
    <?php
    /**
     * Template Name: Front Page Template
     */
    
    get_header(); ?>
    
    <div id="content">
    
       <div id="poster">
          <a href="/<?php echo get_stylesheet_directory_uri(); ?>/images/Vegan-Food-Pyramid-New.jpg"><img class="product-img" src="/<?php echo get_stylesheet_directory_uri(); ?>/images/Vegan-Food-Pyramid-New.jpg" /></a>
          <div class="description">
             <h2>Poster</h2>
             <p>A 30×20-inch poster illustrating over 125 vegan food items as an alternative to the traditional food pyramid. This poster will catch people’s attention and serve as a suggestion for food ideas.</p>
             <h3>$30 each</h3>
             <p>Includes free shipping worldwide</p>
             <a class="button" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=2FKQT879CXYYG">Buy</a>
          </div>
       </div>
    
       <div id="postcard">
          <a href="/<?php echo get_stylesheet_directory_uri(); ?>/images/Vegan-Food-Pyramid-New.jpg"><img class="product-img" src="/<?php echo get_stylesheet_directory_uri(); ?>/images/postcard-splash.jpg" alt="Postcard Splash" /></a>
          <div class="description">
             <h2>Postcards</h2>
             <p>Beautiful 4×6 postcards that can be mailed and shared with friends and family. Hand them out at events. Post them on walls. Share the vegan love!</p>
             <h3>$50 for 50</h3>
             <p>Includes free shipping worldwide</p>
             <a class="button" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=EN387WHNSSFMW">Buy</a>
          </div>
       </div>
    
    </div> <!-- end #content -->
    
    <?php get_footer(); ?>
    

    Explanation

    The front-page.php template begins and ends with a reference to the header and footer that we’ve just prepared. In between, we’ll merge the rest of the HTML, and we’ll use the get_stylesheet_directory_uri function, which will dynamically generate references to the images folder in our new theme.

    5. Standard Page Template

    With the header and footer done, the standard templates are usually quite easy. For brevity’s sake, we’ll go directly to the merged templates.

    Merged Template (page.php)

    
    <?php
    /**
     * The template for displaying all pages.
     */
    
    get_header(); ?>
    
    <div id="content">
    
       <?php while ( have_posts() ) : the_post(); ?>
    
          <?php get_template_part( 'content', 'page' ); ?>
       
       <?php endwhile; ?>
    
    </div>
    
    <?php get_footer(); ?>
    

    Content Template (content-page.php)

    
    <?php
    /**
     * The template used for displaying page content in page.php
     */
    ?>
    
       <article <?php post_class(); ?>>
          <?php the_content(); ?>
       </article>
    
    

    Explanation

    There are several items to point out here:

    • The loop
      If you’re new to WordPress or programming in general, this piece of code in the #content container might look intimidating. The “loop” is code used by WordPress to display a post’s content. You can learn more about the loop in the Codex. Meanwhile, just make sure that it’s in there, or else the content you save in WordPress won’t show up.
    • get_template_part
      Our page template here employs the handy get_template_part function, which is a great way to keep content organized, especially in complex projects. Our website is simple enough not to warrant it, but I left it in just to show you.
    • post_class
      I also added a reference to <article> (with the corresponding post_class function) to make further customization of the design easier.

    5. Full-Width Template (full-width.php)

    Although not illustrated in the screencast, the design includes a full-width template for use on the “Wallpaper” page, while the standard page template is changed to a narrow width.

    Let’s have a look.

    Merged Template (templates/full-width.php)

    
    <?php
    /**
     * Template Name: Full-Width Template
     */
    
    get_header(); ?>
    
    <div id="content" class="full-width">
    
       <?php while ( have_posts() ) : the_post(); ?>
    
          <?php get_template_part( 'content', 'page' ); ?>
       
       <?php endwhile; ?>
    
    </div>
    
    <?php get_footer(); ?>
    

    Explanation

    With the template created, all that remains is to assign it to a page. From the “Edit Page” interface, find the “Page Attributes” box (usually right below the “Publish” box) and select “Full-Width Template” from the “Templates” dropdown menu.

    6. Extras

    Now let’s tackle some of the “extras” that sometimes come up as challenges during a WordPress migration.

    • Breadcrumbs
      Breadcrumbs are relatively common on websites. The easiest way to reproduce them is with a plugin. My current favorite is Breadcrumb NavXT (free). WordPress SEO also offers built-in breadcrumbs.
    • Widgets
      If the design you’re migrating has a sidebar, you could either reproduce it as is (the migration theme has a sample sidebar in place) or integrate WordPress widgets to allow for a dynamically managed sidebar. The folks at Automattic have prepared a handy guide to widgetizing themes. Start there.
    • Restricted content
      In case some content needs to be restricted, WordPress offers basic password protection by default. If you want more control, use a plugin. For basic role management and content permissions, I recommend Members (free). For more advanced control (especially if payment is involved), consider Membership (which has basic and premium versions), s2Member (also free and premium) and WP-Members (free).
    • Custom Post Types
      Some migrations, especially ones with a lot of different types of content, call for “custom post types.” You can learn about custom post types in the Codex. To set them up, I recommend using a plugin. Two good choices are Custom Post Type UI and Types (both free).

    Review Website

    Now that we’ve wrapped up work on the theme, it’s time for a review. Work carefully through the pages on the migrated website. For a large website, focus on the different templates. As you review, here are some things to watch out for:

    1. Broken links
      Make sure all links work as they should. If you have only a few pages, you can check manually. For an automated check, use Integrity (free, for Mac) or Xenu’s Link Sleuth (free, for Windows).
    2. Broken styles
      Occasionally, for one reason or another, a design element of your website might have broken during the migration. Carefully compare the old HTML to the new to make sure you haven’t missed any important code and that the corresponding style sheet rules have been carried over. If all else fails, a quick rebuild of the design element on the new website might be in order.
    3. Broken functionality
      Test any functionality that you’ve migrated over, such as “Buy now” buttons, contact forms, newsletter opt-ins, “members-only” content, embedded maps, media players, etc.
    4. Temporary links
      Depending on how you’ve carried out the migration, temporary links to a subfolder or testing domain might appear in your content or theme. You’ll want to update these before going live. Use the Search and Replace plugin (free) to check for and update links in your content.

    Setting Up Redirects

    If your link structure has changed (and it usually will, even if only slightly), make sure that visitors are redirected from the old pages to the new. For small amounts of content, one of the easiest ways to set up redirects is by adding them to the .htaccess file.

    Open the .htaccess file in the WordPress directory. If you don’t see it, set your FTP client to show hidden files. Now, create redirect rules for each of the old pages. Be sure to put these rules after WordPress’ block of rules.

    Here are the rewrite rules for our links:

    
    Redirect 301 /wallpaper.php http://veganfoodpyramid.com/wallpaper/
    Redirect 301 /about.php http://veganfoodpyramid.com/about/
    Redirect 301 /contact.php http://veganfoodpyramid.com/contact/
    Redirect 301 /contactthanks.php http://veganfoodpyramid.com/contact/thanks/
    

    If editing your .htaccess file is not an option or if you’re dealing with a lot of redirects, then have a look at Redirection (free).

    Advanced tip: If the volume of redirects is very high (which is likely with a large-scale migration and a custom importing process), then consider building a function that hooks into template_redirect, compares a generated list of cases, and then uses the wp_redirect function to redirect any matches.

    Going Live

    Going live with a website usually involves one of two tasks:

    1. Relocate WordPress from the development folder to the root directory.
    2. Point the domain name from the old server to the new WordPress server.

    Relocating WordPress

    If you set up WordPress in a subfolder (as we did), then going live involves a few simple steps. Follow the guide to using a pre-existing subdirectory installation.

    Once you’ve made the change, check immediately for any broken links that you may have missed in the final review.

    Pointing to a New Server

    If you set up WordPress on a new server, then you probably used a temporary domain. Accordingly, remove references to the temporary domain before pointing the domain to the new server.

    Also, if you’re planning to update the name servers for your domain, then first resolve any dependencies in the current DNS records (such as hosted email and third-party services). I usually go live with a domain by updating the A records, leaving the name servers in place.

    Conclusion

    And there you have it! A successful WordPress migration is all about the details, and while this guide is by no means comprehensive, you now have a good outline of the process and a sense of some of the challenges you’ll encounter, along with ideas for solving them. If you run into challenges along the way, share them in the comments below. Now get migrating!

    (al)


    © Jonathan Wold for Smashing Magazine, 2013.

  5. A Client- And Server-Side Approach: Providing The Best Mobile User Experience Possible

      

    Now and again, I hit the swimming pool. It’s a good way to exercise, but also to relax after a long day in front of my PC. I can do quite a few laps in my front crawl, but only because I don’t use my legs much. I kick steadily to ensure that my legs stay lifted and don’t slow me down. I don’t use my legs much for forward propulsion. An instructor once explained to me that legs can definitely help with propulsion in the front crawl, but only at the cost of much higher energy consumption.

    He also explained that champions use their legs a lot. Their hearts are powerful, and they can happily sacrifice the extra effort for the small yet significant gain in speed. People with modest competitive ambitions are typically better off with moderate leg usage.

    Does this relate to mobile Web development, responsive Web design and server-side device detection?

    The analogy is a stretch, but yes, it does. As the inventor of WURFL, I used to live in a world where mobile devices were so limited in capabilities that there was no way a commercial website and its corresponding mobile website could be supported through a unique set of HTML pages without the support of some server-side logic. Strategies to detect and tweak content for mobile devices varied from simple detection scripts to the adoption of full-fledged device description repositories (DDR) such as WURFL.

    Today, things have, to a large extent, changed. Many still have a feature phone, but the majority of users who care about accessing the Internet from their mobile devices will have a smartphone. A 2013 smartphone means the following: a fast connection, a great WebKit-based browser, a 320-pixel wide (or wider) touchscreen and a great operating system that allows for the installation of apps.

    This evolution has turned the mobile Internet into a swimming pool available to every webmaster. Programming strategies such as progressive enhancement (PE) and responsive Web design (RWD) enable everyone to make their full websites usable enough on smartphones from a single set of HTML pages — i.e. with no need for server-side device detection. This is awesome. Webmasters can now make their websites more mobile-friendly without introducing a significant amount of extra complexity. Yet, just like in my initial analogy, the saving is only achieved at the cost of sacrificing certain aspects of the mobile UX that “champions” would not be OK with sacrificing.

    In a previous article by Ronan Cremin and me, “Server-Side Device Detection: History, Benefits and How-To,” we explored the different aspects of client-side approaches versus server-side approaches, and we concluded that server-side strategies still offer a lot to mobile Web developers. I won’t repeat it here; rather, I will go one step further and explain how the two worlds can happily coexist for everyone’s benefit.

    Client-Side Vs. Server-Side: A False Dichotomy

    Most IT people are familiar with the saying, “When all you have is a hammer, every problem looks like a nail.” This is perfectly applicable to mobile development, where, in my experience, developers with a JavaScript and CSS background tend to favor client-side solutions to the problem of device diversity, while developers with traditional system development skills find server-side approaches more natural.

    Unsurprisingly, there are pros and cons to both approaches, and, more importantly, the two approaches are not mutually exclusive and can be made to work together. After all, for any organization that offers a website, the ultimate purpose is to create the greatest user experience possible for its users within the constraints of the project’s timeline and budget.

    Best Of Both Worlds

    When it comes to building a strategy for a website that is friendly to mobile users, there is a whole range of possibilities. At one extreme, a designer might adopt a purely responsive website because they cannot afford to maintain a server-side detection component (or simply because they do not find enough value in the extra complexity). At the other extreme are large companies whose websites (and mobile websites) address particular quirks of popular devices. This approach requires an investment and dedicated team so large that typically only major Internet companies (think Facebook, Yahoo and Google) would go for it.

    Most other companies will find the optimum point somewhere between the two extremes by segmenting the world of connected users in ways that make the most sense in their markets. Such segmentation will need to rely on some form of server-side detection.

    One way to put it is that one should adopt a “best of both worlds” hybrid approach. In this article, I will show an example of this.

    Every software project is one-off. The Web is no exception. Nor is mobile Web development, where the super-rapid progress of mobile devices is constantly turning best practices into moving targets. For this article, I figured that nothing could make the point better than a real example with real code.

    My example is a cross-browser and cross-device slideshow. I will show how server-side and client-side detection can be made to work together to deliver a great UX on a variety of clients.

    Segmentation (Good Ol’ Divide And Conquer)

    The slideshow will be made available to the following classes of HTTP clients:

    • non-smartphones (or feature phones),
    • smartphones,
    • tablets and desktops.

    I have always called these “segments,” and I have referred to the splitting up into segments as “segmentation.” The key point is that each segment will be provided with a fundamentally different UI structure. Such segmentation will be supported through server-side detection.

    Within each segment, there will still be space for further optimization of the UX. Such optimizations will happen with RWD and device detection. Notably, this approach will be used to obtain pictures in different sizes and to address the bandwidth problem, particularly for mobile devices.

    Let’s start by sketching the different UIs for the different classes of HTTP clients (i.e. segments).

    Non-Smartphones

    Non-smartphones are commonly referred to as feature phones in the industry. There is no standard definition of what a smartphone is, but a device that possesses the following features would likely be called a smartphone by most:

    • touchscreen;
    • a screen that is 240-pixels wide or wider;
    • Android 2.2, iOS, Windows Phone 7.5 or higher, RIM OS 7 or higher, Symbian Belle or higher, Nokia N9 WebKit-based browser;
    • not a tablet.

    This is a totally arbitrary definition, but good enough for the purpose of this article.

    Devices that do not support one or more of the above features will be considered feature phones.

    Because no assumption can be made for non-smartphones, we will assume a small screen, no touchscreen and limited bandwidth (which entails the need to minimize the number of HTTP requests required to download all of the content).

    Please note that the lack of a touchscreen might require users to click the “down” button multiple times to get to the icon they wish to select.

    The following wireframe nicely illustrates what we are getting at:


    Feature phones (i.e. non-smartphones) have relatively small screens (typically narrower than 240 pixels). The presence of a touchscreen should not be assumed for devices in this segment.

    Smartphones

    Smartphones have a large screen, and users don’t have to click their way through icons to get to the one they want. They simply touch it. Because of this, a UI such as the following is better suited to them:


    Smartphones have large screens (240 pixels or wider). The presence of a touchscreen and of basic media queries for changes in orientation may be safely assumed.

    Tablets and Desktops

    In the case of tablet and desktop browsers, we can safely assume that a large screen is available. In this case, consolidating the two views (i.e. the navigation and the actual picture) into a single screen makes sense:


    A screen 700 pixels wide (or wider) may be assumed.

    Of course, I created a single segment for tablets and desktops for illustrative purposes, but a real project might segment differently, based on the business model of the organization and the traffic it sees from different classes of devices.

    Before delving into the code to implement this, I should discuss a few aspects of mobile development.

    Important Note About Mobile Bandwidth: Speed Isn’t Everything

    US carriers (i.e. network operators) boast in their advertising about their increasingly faster 4G networks and the blazing download speeds that their customers can get. My experience (and the experience of others) is that those figures are sometimes truthful under good network conditions, as in the case of a large single download or of video streaming. In practice, things are a bit more complicated. The overhead of establishing an HTTP connection in mobile is high.

    Many browsers and devices open only one or two concurrent connections with the server (partly because of what the HTTP specification says, and partly because of hardware limitations). Keep-alives cannot be assumed to always work as one would expect in mobile, because of strategies that the devices follow to save battery power.

    The problem is at the lower levels and is rooted in the fact that mobile networks and TCP/IP were not built to play well together to begin with.

    Techniques such as “domain sharding” (i.e. fooling the browser into believing it’s talking to different servers) help to increase the number of concurrent connections. However, if you want to increase the download speed (both real and perceived) of a website, limiting the overall number of HTTP connections is your best bet.

    May Your Days Be Merry And Your URLs Unique

    People share links on Twitter, Facebook, Google+ and a lot of other services these days. This is good, but it has also exposed a shortcoming with a popular approach to managing the mobile channel — i.e. creating a separate mobile website (with separate URLs to the mobile view of the content). In short, a user will share http://m.coolsite.com on Twitter, and users on desktops and tablets will be offered a sucky UI. Having http://www.coolsite.com serve both the Web and mobile experience would effectively solve the problem.

    As my last article explains, there are ways to have a single URL “multi-serve” content for different media. Of course, this requires a bit more design and work from the service architect as compared to purely client-side approaches.

    In the case of PE and RWD, the “uniqueness” of the URL comes free of charge. In the case of server-side detection, a strategy to multi-serve content from a unique URL needs to be designed into the system. We will see one way to achieve this in the code discussed further down.

    Content = Content + Presentation? A Little (But Important) Aside

    Ethan Marcotte, arguably the inventor of RWD, correctly identifies the URL issue in his book Responsive Web Design:

    “I do think fragmenting our content across different “device-optimized” experiences is a losing proposition, or at least an unsustainable one.”

    This sentence has been quoted endlessly, and it seems hard to disagree with. Yet, it contains an ambiguity that makes it very debatable, to say the least. What Ethan calls “content” has historically been referred to as “presentation” by most. In fact, I could easily argue that separation of content and presentation is the foundation of a plethora of Web programming frameworks, such as model-view-controller (MVC), but also Windows DNA in the late ’90s.

    While I am aware that designers will argue that the difference between content and presentation is blurry (advertising is the best example of this), such a differentiation has been very helpful to Web programmers in multiple ways over the past 15 years. In general, professionals are much better off preserving this separation, rather than blurring the difference between the two.

    Software architects should obviously not fragment the content managed by their system. At the same time, they should be ready to multi-serve the presentation of the same data to users of different media and different devices in the name of an optimal UX. I would go so far as to argue that PE and RWD are also about providing multiple presentations of the same content, inasmuch as the clever use of grids and media queries allows developers to confine the “multi-serving framework” to a single page.

    End of the aside.

    Getting back to URL uniqueness, it is obvious that, in the case of server-side detection, a URL strategy must be designed with extra use of resources. Of course, webmasters have managed similar issues all their careers. Internationalizing a website presents the same challenges: one could have content served in multiple languages from the same URL (or even JSP or PHP page) or simply provide sibling websites, one for each supported language. Support for the potential lack of JavaScript presents a similar issue, as does the fact that an international content provider may wish to offer different (i.e. more relevant) content to visitors from different geographic regions, even where the language is the same. Supporting this means extra effort and cost. Typically, after the cost versus benefit equation is solved, some companies will go for the benefit in spite of the cost.

    After so many words, let us see how the following code implements everything we’ve illustrated above.

    The Code

    Everything that has been discussed so far is illustrated in practice with a self-contained example that I built (along with my friend Steve Kamerman, COO at ScientiaMobile) to reinforce the points in this article. Be aware that, for the sake of clarity, the example hardwires many of the resources that would normally be isolated in separate databases or configuration elements.

    Here is a list of the main components in the code:

    • a DDR;
    • an MVC framework;
    • a controller with the segmentation logic;
    • a server-side image-resizing framework;
    • the views — feature phone, smartphone and tablet/desktop, in our case.

    Let’s discuss each of them.

    Device Description Repository

    A DDR is a software framework that enables an application to associate an HTTP request with the properties of the client (Web browser, mobile device, Internet-enabled wristwatch, etc.). In our example, I will be using ScientiaMobile’s DDR, WURFL Cloud, because it’s the easiest to install on all platforms and also comes with a free offering for those who want to play around with it.

    Of course, any other DDR could be used in place of WURFL Cloud, including AGPL-licensed WURFL or other open-source frameworks based on user-agent string analysis through regular expressions.

    For the purpose of this article, here is the core bit of code that explains how to use the DDR (in the index.php file):

    :
    require_once dirname(__FILE__).'/lib/WurflCloudClient/Client/Client.php';
      :
    
    // Disable caching for testing
    $cache_enabled = false;
    
    $wurfl_config = new WurflCloud_Client_Config();
    $wurfl_config->api_key = 'XXXXX:YYYYYYYYYYYYYYYYYYYYYYYYYYY';
      :
    if ($cache_enabled) {
    	$wurfl = new WurflCloud_Client_Client($wurfl_config);
    } else {
    	$wurfl = new WurflCloud_Client_Client($wurfl_config, new WurflCloud_Cache_Null());
    	header("Cache-Control: no-cache, must-revalidate");
    	header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
    }
    $wurfl->detectDevice();
    

    Note: The cache is disabled because this is handy for testing purposes. But you’ll want to enable it on a production website, or else every HTTP request from your users will be a request to the cloud.

    Once this code has run, you will be able to look up device capabilities on your server, without any need to interact with the client through JavaScript or the like, as simply as this:

    
    $wurfl->getDeviceCapability('is_tablet')
    

    All of the magic of looking up the HTTP request and recovering a profile for the device is happening under the hood.

    Model-View-Controller Framework

    MVC is a popular programming pattern among Java developers that over the years has made inroads among programmers of other languages (including PHP). In short, the MVC framework analyzes an incoming HTTP request and “dispatches” the actual handling to a different PHP page that has been deemed to be more apt for the job. In our case, the framework will route the HTTP request to the PHP page that would implement the best UI for that “segment.”

    For the record, the MVC framework we’re using in our example is homemade, but Steve explains that it was inspired by a micro-framework named Silex.

    The framework itself is implemented in the lib/SimpleApp.php file:

    
    require_once dirname(__FILE__).'/lib/SimpleApp.php'; 
      :
    $app = new SimpleApp();
    

    Once the MVC framework is included, dispatching an HTTP request to the right view (see below) is as simple as this:

    
    $app->render('image/smartphone.php', $view_data);
    

    The interesting part is that the URL will not be affected by this. Users will only see the index.php page that responded to the request. This effectively solves the problem of URL uniqueness that we discussed above.

    Controller

    The controller (the “C” in MVC) is in charge of segmentation (i.e. deciding the view to which a certain HTTP client should be directed based on its profile). Here is the core of the controller (in index.php):

    
    if ($wurfl->getDeviceCapability('is_smartphone')) {
    	$app->render('index/smartphone.php', $view_data);
    } else if ($wurfl->getDeviceCapability('is_mobile') 
    && !$wurfl->getDeviceCapability('is_tablet')) {
    	$app->render('index/featurephone.php', $view_data);
    } else {
    	$app->render('index/desktop.php', $view_data);
    }
    

    In light of what we have explained, this part should be rather self-explanatory: smartphone.php handles smartphones, featurephone.php handles feature phones, and everything else (including tablets) is handled by desktop.php. There are actually two sets of views, one that manages the discovery page (i.e. the thumbnails with pictures) and one that represents the single picture.

    The is_smartphone capability is a so-called “virtual capability” — i.e. a computed property that relies on other capabilities and that represents ScientiaMobile’s understanding of what a smartphone is. A lot of people find this handy. Of course, nothing prevents a WURFL user from choosing the capabilities and rolling a particular segmentation that make the most sense for their business model.

    Image Resizing (RESS)

    RESS stands for “responsive images and server-side components,” making it the most screwed-up abbreviation I have ever seen in my life. Because it is now common, though, I will use it, too. The premise of RESS is fairly reasonable: RWD is cool, but sending 500 KB pictures to a mobile device is not a good idea for a variety of reasons. This is why even the most inveterate RWD promoters will concede that resizing pictures on the server in order to speed up downloading and rendering on mobile devices is still a good idea. Of course, CSS and JavaScript files are also resources that you’ll want to make as light as possible. These also fall under the RESS umbrella.

    Users of WURFL Cloud also have access to a service called Image Resizer. In short, Image Resizer enables you to create a URL that piggybacks the following bits onto itself:

    • the URL of the original picture,
    • a combination of parameters that specify how the picture should be resized and manipulated.

    Requesting the URL will result in a picture with the desired features being obtained. For the record, other services of this kind are around, such as Sencha.io Src and the up-and-coming WhateverWeb, which promises to go beyond simple image resizing. Call me a romantic, but I prefer that we eat our own dog food for this example.

    A photographer also graciously gave me some pictures of Chicago for this article, which I’ve hosted at http://cto.scientiamobile.com/chicago/ (i.e. in a place where Image Resizer can pick them up):

    Let’s see how Image Resizer is used in practice (see views/index/smartphone.php):

    
    // Compute the size of the image thumbnails
    $thumb_width = 95;
    $thumb_height = 95;
    $rszr_tumbnail = "http://rszr1.wurflcloud.com/234341/w_$thumb_width/
                      h_$thumb_height/m_cropbox/";
      :
    <div style="width: 100%; float: left; margin: 5px;">
      <?php foreach ($images as $id => $image) { ?>
       <div style="float: left; margin: 5px;">
          <a href="/<?php echo $app->getUriPrefix().'/image/'.$id; ?>">
            :
           <img alt="" src="/<?php echo $rszr_tumbnail.$image['src']; ?>" />
          </a>
        </div>
      <?php } ?>
    </div>
    

    This will generate markup like the following snippet:

    
    <div style="float: left; margin: 5px;"><a href="/smash/image/1"><img alt="" src="http://rszr1.wurflcloud.com/234341/w_95/ h_95/m_cropbox/http://cto.scientiamobile.com/chicago/chicago2.jpg" /></a></div>
    

    In reality, I’ve cheated a bit. I cut some interesting bits from the code above. In particular, I’ve removed a trick to use a really important technique called the data URI scheme, which enables developers to nest pictures in the HTML itself in the form of ASCII Base64 garbage. As you can imagine, not all devices support the feature (although smartphones usually do). This is where WURFL’s image_inlining capability, along with the ability of the image resizer to provide the picture already in Base64 format, comes in handy. The image_inlining will tell you whether the data URI scheme is supported:

    
    $image_inlining = $wurfl->getDeviceCapability('image_inlining');
    if ($image_inlining) {
    	$rszr_tumbnail = "http://rszr1.wurflcloud.com/234341/w_$thumb_width/
                             h_$thumb_height/m_cropbox/in_true/"; } else {
    	$rszr_tumbnail = "http://rszr1.wurflcloud.com/234341/w_$thumb_width/
                             h_$thumb_height/m_cropbox/";
    }	
      :
    <div style="width: 100%; float: left; margin: 5px;"<
    <?php foreach ($images as $id => $image) { ?>
      <div style="float: left; margin: 5px;">
        <a href="/<?php echo $app->getUriPrefix().'/image/'.$id; ?>">
        <?php if ($image_inlining) { ?>
          <img alt="" src="/<?php echo file_get_contents($rszr_tumbnail.$image['src']); ?>"/> 
        <?php } else { ?>
          <img alt="" src="/<?php echo $rszr_tumbnail.$image['src'];?>"/> 
        <?php } ?> 
      </a></div>
    <?php } ?>
    </div>
    

    In the case of a device that supports image inlining, the code above will produce the following:

    
    <div style="float: left; margin: 5px;">
    <a href="/smash/image/1"> <img alt="" src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2QtanBlZ..
      :
    AUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlN
       : 
    cH14z9RXHTc6jb6dWdM3GmrdT//Z" /> </a>
    </div>
    

    As we discussed earlier, this is particularly crucial because of the importance of minimizing the number of HTTP requests demanded by a mobile device to download a page, an aspect that is simply not worth optimizing in classic Web programming: too much extra work for way too little gain.

    Of course, the data URI scheme will greatly increase the perceived download speed on smartphones and non-smartphones alike.

    The Views: Feature Phone, Smartphone and Desktop/Tablet

    The three segments we initially defined map one to one with our three views (feature phone, smartphone and tablet/desktop), according to the MVC paradigm. Each view offers a user experience that is best suited to the respective class of devices and browsers.

    It goes without saying that adopters of a DDR still retain control over the UX of a deployed application simply by configuring a device to access a given view (for example, by downgrading a misbehaving smartphone to the feature-phone view).

    The feature-phone view is particularly interesting because you’ll want to serve XHTML Mobile Profile (XHTML MP) as a markup to those devices. Developers who approach mobile today might get away with ignoring XHTML MP, but for years XHTML MP has been the standard mobile Web markup. Still today, smartphones will immediately recognize a website created in XHTML MP as being a mobile website, even when no viewport meta tag is available. Be aware that XHTML MP is typically better served with a different MIME type than text/html.

    Note: Covering XHTML MP is beyond the scope of this article. If you are curious about the world of mobile programming on feature phones, my document “Global Authoring Practices for the Mobile Web” enjoyed some popularity for some time. Most people find it very informative still today.

    The following screenshots visualize what the different UIs mean in practice:


    The view on feature phones.


    The view on smartphones.


    The view on tablets and desktop. Above: The page on an iPad.


    Here is the same page on the Xbox 360 (IE 10).

    Of course, this example is just a proof of concept. Nothing prevents a programmer from making the desktop view even more responsive than it already is, or from adopting something like the good PhotoSwipe to provide interactive slideshows on smartphones and tablets (but not on older phones, where they would be unlikely to work). Divide and conquer.

    Conclusion

    Purely client-side approaches such as RWD and PE can make Web pages accessible on smartphones. For companies and organizations, this means that supporting mobile devices could be cheaper now than it was a couple of years back. Yet, these savings come at the cost of sacrificing certain aspects of a full-fledged cross-channel Web offering.

    Large organizations may still want to adopt server-side device detection in some form to deliver a great UX to everyone who accesses their websites. While RWD and PE strategies can (and should) be adopted by companies, a hybrid client- and server-side approach is the most likely to deliver a great service to desktop, tablet and mobile users alike.

    We’ve discussed an instance of such a hybrid approach by showing how segmentation, server-side resized images and the data URI scheme are key components to a great user experience across devices and browsers.

    Have a look at the demo app.

    (al) (ea)


    © Luca Passani for Smashing Magazine, 2013.