Skip navigation
Help

Markup languages

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

  

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

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

The State Of Images In Responsive Web Design

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

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

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

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

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

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

The code in the proposed specification looks like this :


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

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

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

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

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


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

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

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

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

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

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


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

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

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

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

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

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

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

Image compression example
Daan Jobsis’ demonstration of image compression.

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

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

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

Four CSS3 Layout Solutions That Address the Flexible Layout Problem

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


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

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

Flexbox as an example

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

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

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

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

CSS3 Multiple Column layout

The syntax looks like this:


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

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

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

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

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


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

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

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

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

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

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

The syntax looks like this:


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

.child1 {
   position: a;
}

.child2 {
   position: b;
}

.child3 {
   position: c;
}

.child4 {
   position: d;
} 

This renders as follows:

CSS3 template layout

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

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

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

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

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

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

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

A Word on Adaptive Typography

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


html {
   font-size: 14px;
}

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

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

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

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

A Better Way To Work Responsively With Other Complex Content

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

Dealing With Forms on a Responsive Website

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

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

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

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

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

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

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

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

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

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

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

Dealing With Tables on a Responsive Website

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

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

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

Responsive table examples
Some examples of responsive tables.

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

Responsive table overflow example
Two examples of scrollable responsive tables

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

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

Responsive table reflow example
Reflowing a table responsively

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

Embedding Third-Party Content: The Responsive Iframe Problem

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

An HTML and CSS Workaround

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


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

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

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

Dealing With Responsive Video In Future

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


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

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

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

Embedding Google Maps

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

We Need Better APIs

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

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

Responsive Navigation: An Overview Of Current Solutions

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

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

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

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

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

Toggle navigation example
Some examples of toggle navigation

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

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

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

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

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

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

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

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

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

Detecting Touch Capabilities With Native JavaScript

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

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

CSS Level 4 “Pointer” Media Query

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

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

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


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

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

CSS Level 4 “Hover” Media Query

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

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


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

   .hovercontent:hover { display: block; }    
 }

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

CSS Level 4 Luminosity Media Query

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

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

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

The code would look something like this:


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

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

More Mobile Capabilities to Detect Using APIs and JavaScript

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

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

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

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

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

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

Rethinking The Way We And The User Deal With Content

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

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

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

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

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

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

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

Conclusion

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

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

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

(al) (ea)

© Stéphanie Walter for Smashing Magazine, 2013.

0
Your rating: None
Original author: 
Todd Hoff

Distributed transactions are costly because they use agreement protocols. Calvin says, surprisingly, that using a deterministic database allows you to avoid the use of agreement protocols. The approach is to use a deterministic transaction layer that does all the hard work before acquiring locks and the beginning of transaction execution.

Overview:
Many distributed storage systems achieve high data access throughput via partitioning and replication, each system with its own advantages and tradeoffs. In order to achieve high scalability, however, today’s systems generally reduce transactional support, disallowing single transactions from spanning multiple partitions. Calvin is a practical transaction scheduling and data replication layer that uses a deterministic ordering guarantee to significantly reduce the normally prohibitive contention costs associated with distributed transactions. Unlike previous deterministic database system prototypes, Calvin supports disk-based storage, scales near-linearly on a cluster of commodity machines, and has no single point of failure. By replicating transaction inputs rather than effects, Calvin is also able to support multiple consistency levels—including Paxos based strong consistency across geographically distant replicas—at no cost to transactional throughput.

If you are interested Daniel Abadi gives a very accessible overview of Calvin in If all these new DBMS technologies are so scalable, why are Oracle and DB2 still on top of TPC-C? A roadmap to end their dominance.

0
Your rating: None
Original author: 
David Storey

  

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

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

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

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

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

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


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

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


html {
   height: 100%;
} 

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

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

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

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

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

   height: 10rem;
}

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

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

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

Enabling Flexbox

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


body {
   display: flex;
}

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

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

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

Centering Horizontally

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


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

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

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

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

Centering Vertically

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


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

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

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

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


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

Flexible Sizes

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

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

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


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

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

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


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

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

Source-Order Independence

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

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

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


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

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

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

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

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

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

Syntax Changes

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

Specification versions

Specification
IE
Opera
Firefox
Chrome
Safari

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

Mid
10 (-ms-)

Old

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

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

Enabling flexbox: setting an element to be a flex container

Specification
Property name
Block-level flex
Inline-level flex

Standard
display
flex
inline-flex

Mid
display
flexbox
inline-flexbox

Old
display
box
inline-box

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

Specification
Property name
start
center
end
justify
distribute

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

Mid
flex-pack
start
center
end
justify
distribute

Old
box-pack
start
center
end
justify
N/A

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

Specification
Property name
start
center
end
baseline
stretch

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

Mid
flex-align
start
center
end
baseline
stretch

Old
box-align
start
center
end
baseline
stretch

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

Specification
Property name
auto
start
center
end
baseline
stretch

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

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

Old
N/A

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

Specification
Property name
start
center
end
justify
distribute
stretch

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

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

Old
N/A

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

Display order: specifying the order of flex items

Specification
Property name
Value

Standard
order

Mid
flex-order
<number>

Old
box-ordinal-group
<integer>

Flexibility: specifying how the size of items flex

Specification
Property name
Value

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

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

Old
box-flex
<number>

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

Direction: specifying the direction of the main flexbox axis

Specification
Property name
Horizontal
Reversed horizontal
Vertical
Reversed vertical

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

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

Old
box-orient

box-direction
horizontal

normal
horizontal

reverse
vertical

normal
vertical

reverse

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

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

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

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

Specification
Property name
No wrapping
Wrapping
Reversed wrap

Standard
flex-wrap
nowrap
wrap
wrap-reverse

Mid
flex-wrap
nowrap
wrap
wrap-reverse

Old
box-lines
single
multiple
N/A

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

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

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

Conclusion

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

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

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

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

Further Reading

(al)

© David Storey for Smashing Magazine, 2013.

0
Your rating: None
Original author: 
(author unknown)

Ilya Grigorik discusses in detail how to construct a mobile website that loads as quickly as possible. A site that not only renders in 1 second, but one that is also visible in 1 second. With hard statistics as evidence to show why this matters, Ilya discusses techniques to deliver a 1000 millisecond experience.

0
Your rating: None
Original author: 
(author unknown)

Web maps have come a long way. Improved data, cleaner design, better performance, and more intuitive controls have made web maps a ubiquitous and critical component of many apps. They’ve also become one of the mobile space’s most successful transplants as more and more apps are powered by location-aware devices. The core web map UI paradigm itself—a continuous, pannable, zoomable surface—has even spread beyond mapping to interfaces everywhere.

Despite all this, we’ve barely begun to work web maps into our design practice. We create icon fonts, responsive grids, CSS frameworks, progressive enhancement strategies, and even new design processes. We tear down old solutions and build new ones, and even take an extra second to share battle stories in prose and in person. Yet nearly five years since Paul Smith’s article, “Take Control of Your Maps,” web maps are still a blind spot for most designers.

Have you ever taken apart a map? Worked with a map as a critical part of your design? Developed tricks, hacks, workarounds, or progressive enhancements for maps?

This article is a long overdue companion to Paul’s piece. Where he goes on a whirlwind survey of the web mapping stack at 10,000 feet, we’re going to walk through a single design process and implement a modern-day web map. By walking this path, I hope to begin making maps part of the collective conversation we have as designers.

Opinionated about open

Paul makes a strong case for why you might want to use open mapping tools instead of the established incumbent. I won’t retread his reasons here, but I would like to expand on his last: Open tools are the ones we hack best.

There is nothing mysterious about web maps. Take any spatial plane, split it up into discrete tiles, position them in the DOM, and add event handlers for panning and zooming. The basic formula can be applied to Portland, Mars, or Super Mario Land. It works for displaying large street maps, but nothing stops us from tinkering with it to explore galleries of art, create fictional game worlds, learn human anatomy, or simply navigate a web page. Open tools bare the guts of this mechanism to us, allowing us to see a wider range of possibilities.

 character navigation, Mars, and Super Mario Land.
The mechanics of web maps are not limited to street maps.

We should know the conditions under which map images are loaded and destroyed; we should argue whether map tiles are best positioned with CSS transforms or not; and we should care whether vector elements are drawn with SVG or Canvas. Open tools let us know and experiment with these working details of our maps. If you wouldn’t have it any other way with your HTML5, CSS, or JavaScript libraries, then you shouldn’t settle for less when it comes to maps.

In short, we’ll be working with a fully open mapping stack. MapBox, where I work, has pulled together several open source libraries into a single API that we publish under mapbox.js. Other open mapping libraries that are worth your time include Leaflet and D3.js.

Starting out

I’m a big fan of Sherlock Holmes. Between the recent Hollywood movies starring Robert Downey Jr. and the BBC’s contemporary series, I’m hooked. But as someone who has never been to London, I know I’m missing the richness of place and setting that Sir Arthur Conan Doyle meant to be read into his short stories.

A typical approach would be to embed a web map with pins of various locations alongside one of the Sherlock stories. With this approach the map becomes an appendix—a dispensable element that plays little part in Doyle’s storytelling. Instead, we’re going to expand the role of our map, integrating it fully into the narrative. It will set the stage, provide pace, and affect the mood of our story.

Comparing a map used as embedded media versus one used as a critical design element.

A tale of places

To establish a baseline for our tale, I restructured The Adventure of the Bruce-Partington Plans to be told around places. I picked eight key locations from the original text, pulled out the essential details of the mystery, and framed them out with HTML, CSS, and JavaScript.

Text only demo.
A Sherlock Holmes story in text only. View Demo 1.

  • The story is broken up into section elements for each key location. A small amount of JavaScript implements a scrolling flow that highlights a single section at a time.
  • Our page is not responsive yet, but it contains scaffolding to guard against bad choices that could thwart us. The main text column is fluid at 33.33% and pins to a min-width: 320px. If our content and design flow reasonably within these constraints, we’re in good shape.

Next, we’ll get started mapping. Initially we’ll work on our map separately from our story page to focus on learning key elements of a new technology.

Maps are data

The mapping equivalent of our abridged Sherlock story is a dataset of eight geographic points. GeoJSON, a format for describing geographic data in JSON, is the perfect starting point for capturing this data:

{
    "geometry": { "type": "Point", "coordinates": [-0.15591514, 51.51830379] },
    "properties": { "title": "Baker St." }
}, {
    "geometry": { "type": "Point", "coordinates": [-0.07571203, 51.51424049] },
    "properties": { "title": "Aldgate Station" }
}, {
    "geometry": { "type": "Point", "coordinates": [-0.08533793, 51.50438536] },
    "properties": { "title": "London Bridge Station" }
}, {
    "geometry": { "type": "Point", "coordinates": [0.05991101, 51.48752939] },
    "properties": { "title": "Woolwich Arsenal" }
}, {
    "geometry": { "type": "Point", "coordinates": [-0.18335806, 51.49439521] },
    "properties": { "title": "Gloucester Station" }
}, {
    "geometry": { "type": "Point", "coordinates": [-0.19684993, 51.5033856] },
    "properties": { "title": "Caulfield Gardens" }
}, {
    "geometry": { "type": "Point", "coordinates": [-0.10669358, 51.51433123] },
    "properties": { "title": "The Daily Telegraph" }
}, {
    "geometry": { "type": "Point", "coordinates": [-0.12416858, 51.50779757] },
    "properties": { "title": "Charing Cross Station" }
}

Each object in our JSON array has a geometry—data that describe where this object is in space—and properties—freeform data of our own choosing to describe what this object is. Now that we have this data, we can create a very basic map.

Basic web mapping demo.
The basics of web mapping. View Demo 2.

  • Note that the coordinates are a pair of latitude and longitude degrees. In the year 2013, it is still not possible to find a consistent order for these values across mapping APIs. Some use lat,lon to meet our expectations from grade-school geography. Others use lon,lat to match x,y coordinate order: horizontal, then vertical.
  • We’re using mapbox.js as our core open source mapping library. Each map is best understood as the key parameters passed into mapbox.map():
    1. A DOM element container
    2. One or more Photoshop-like layers that position tiles or markers
    3. Event handlers that bind user input to actions, like dragging to panning
  • Our map has two layers. Our tile layer is made up of 256x256 square images generated from a custom map on MapBox. Our spots layer is made up of pin markers generated from the GeoJSON data above.

This is a good start for our code, but nowhere near our initial goal of using a map to tell our Sherlock Holmes story.

Beyond location

According to our first map, the eight items in our GeoJSON dataset are just places, not settings in a story full of intrigue and mystery. From a visual standpoint, pins anonymize our places and express them as nothing more than locations.

To overcome this, we can use illustrations for each location—some showing settings, others showing key plot elements. Now our audience can see right away that there is more to each location than its position in space. As a canvas for these, I’ve created another map with a custom style that blends seamlessly with the images.

Web map with illustrations.
Illustrations and a custom style help our map become part of the storytelling. View Demo 3, and then read the diff.

  • The main change here is that we define a custom factory function for our markers layer. The job of the factory function is to take each GeoJSON object and convert it to a DOM element—an a, div, img, or whatever—that the layer will then position on the map.
  • Here we generate divs and switch from using a title attribute in our GeoJSON to an id. This provides us with useful CSS classes for displaying illustrations with our custom markers.

Bringing it all together

Now it’s time to combine our story with our map. By using the scroll events from before, we can coordinate sections of the story with places on the map, crafting a unified experience.

Web map coordinated to story text by a scroll handler.
As the user reads each section, the map pans to a new location. View Demo 4, then read the diff.

  • The bridge between the story and the map is a revamped setActive() function. Previously it only set an active class on a particular section based on scrolling position. Now it also finds the active marker, sets an active class, and eases the map to the marker’s location.
  • Map animation uses the easey library in the mapbox.js API, which implements animations and tweening between geographic locations. The API is dead simple—we pass it the lon,lat of the marker we want to animate to, and it handles the rest.
  • We disable all event handlers on our map by passing an empty array into mapbox.map(). Now the map can only be affected by the scrolling position. If users wanted to deviate from the storyline or explore London freeform, we could reintroduce event handlers—but in this case, less is more.

Displaying our fullscreen map together with text presents an interesting challenge: our map viewport should be offset to the right to account for our story on the left. The solution I’m using here is to expand our map viewport off canvas purely using CSS. You could use JavaScript, but as we’ll see later, a CSS-only approach gives us elegant ways to reapply and adjust this technique on mobile devices.

Using an off-canvas map width to offset the viewport center.

At this stage, our map and story complement each other nicely. Our map adds spatial context, visual intrigue, and an interesting temporal element as it eases between long and short distances.

Maps in responsive design

The tiled, continuous spatial plane represented by web maps is naturally well-suited to responsive design. Web maps handle different viewport sizes easily by showing a bit more or a bit less map. For our site, we adjust the layout of other elements slightly to fit smaller viewports.

Adding a responsive layout.
Tweaking layout with web maps. View Demo 5, then read the diff.

  • With less screen real estate, we hide non-active text sections and pin the active text to the top of the screen.
  • We use the bottom half of the screen for our map and use media queries to adjust the map’s center point to be three-fourths the height of the screen, using another version of our trick from Demo 4.

With a modest amount of planning and minimal adjustments, our Sherlock story is ready to be read on the go.

Solve your own case

If you’ve been following the code between these steps, you’ve probably noticed at least one or two things I haven’t covered, like the parameters of ease.optimal(), or how tooltips picked up on the title attribute of our GeoJSON data. The devil’s in the details, so post to this GitHub repository, where you will find the code and the design.

You should also check out:

  • The MapBox site, which includes an overview of tiling and basic web map concepts, and MapBox.js docs and code examples.
  • Leaflet, another powerful open source mapping library.
  • D3.js, a library for powering data-driven documents that has a broad range of applications, including mapping.

This example shows just one path to integrating web maps into your designs. Don’t stick to it. Break it apart. Make it your own. Do things that might be completely genius or utterly stupid. Even if they don’t work out, you’ll be taking ownership of maps as a designer—and owning something is the only way we’ll improve on it.

0
Your rating: None
Original author: 
Scott Gilbertson

Look Ma, no floats! Image: Abobe

HTML5 and CSS 3 offer web developers new semantic tags, native animation tools, server-side fonts and much more, but that’s not the end of the story. In fact, for developers slogging away in the web design trenches, one of the most promising parts of CSS 3 is still just over the horizon — true page layout tools.

While it’s possible to create amazingly complex layouts using tools like CSS floats, positioning rules and the odd bit of JavaScript, none of those tools were actually created explicitly for laying out content, which is why it’s amazingly complex to get them working the way you want across browsers.

Soon, however, you’ll be able to throw out your floats and embrace a better way — the CSS Flexible Box Model, better known as simply Flexbox. Flexbox enables you to create complex layouts with only a few lines of code — no more floats and “clearfix” hacks.

Perhaps even more powerful — especially for those building responsive websites — the Flexbox order property allows you to create layouts completely independent of the HTML source order. Want the footer at the top of the page for some reason? No problem, just set your footer CSS to order: 1;. Flexbox also makes it possible to do vertical centering. Finally.

We’ve looked at Flexbox in the past, but, unfortunately the spec has undergone a serious re-write since then, which renders older code obsolete. If you’d like to get up to speed with the new syntax, the Adobe Developer Blog recently published a guide to working with Flexbox by developer Steven Bradley.

Bradley walks through the process of using Flexbox in both mobile and desktop layouts, rearranging source order and elements to get both layouts working with a fraction of the code it would take to do the same using floats and other, older layout tools. The best way to wrap your head around Flexbox is to see it in action, so be sure to follow the links to Bradley’s demo page using either Chrome, Opera or Firefox 20+.

For some it may still be too early to use Flexbox. Browser support is improving, but obviously older browsers will never support Flexbox, so bear that in mind. Opera 12 supports the new syntax, no prefix necessary. Chrome supports the new syntax, but needs the -webkit prefix. Like Opera, Firefox 20+ Firefox 22 supports the unprefixed version of the new spec. Prior to v22 (currently in the beta channel), Firefox supports the old syntax. IE 10 supports the older Flexbox syntax. Most mobile browsers support the older syntax, though that is starting to change. [Update: Mozilla developer Daniel Holbert, who is working on the Flexbox code in Firefox, wrote to let me know that the Flexbox support has been pushed back to Firefox 22. Actually the new Flexbox syntax is part of Firefox 20 and up, but until v22 arrives it's disabled by default. You can turn it on by heading to about:config and searching for layout.css.flexbox.enabled pref. Set it to true and the modern syntax will work.]

So, as of this writing, only two web browsers really support the new Flexbox syntax, though Firefox will make that three in the next month or so.

But there is a way to work around some of the issues. First off, check out Chris Coyier’s article on mixing the old and new syntaxes to get the widest possible browser support. Coyier’s methods will get your Flexbox layouts working in pretty much everything but IE 9 and below.

If you’re working on a personal site that might be okay — IE 9 and below would just get a simplified, linear layout. Or you could serve an extra stylesheet with some floats to older versions of IE (or use targeted CSS classes if you prefer). That defeats some of the benefits of Flexbox since you’ll be writing floats and the like for IE, but when usage drops off you can just dump that code and help move your site, and the web, forward.

0
Your rating: None

By Dominique Hazaël-Massieux: People used to stare at me and laugh, back in 2005 when W3C launched its Mobile Web Initiative to advocate the importance of the web to the mobile world. Now I am the one smiling much of the time, as I did most recently during the 2013 edition of the Mobile World Congress (MWC) in Barcelona, one of the largest events to focus on mobile devices and networks.

This year W3C had a huge HTML5 logo splashed across its booth to emphasize the impact of the Open Web Platform across industries and devices. But the real adoption story was told by the HTML5 logos prominent at many, many other booths. The web has gained real visibility on mobile, and we should all be smiling because we are all getting closer to a platform for reaching more people on more devices at lower cost.

MWC 2013 also confirmed that HTML5 has broken out of the browser. We are seeing more and more HTML5-based development platforms, such as PhoneGap, Windows 8, Blackberry, and Tizen. Mozilla’s big announcement at MWC 2013 centered on FirefoxOS, Mozilla’s mobile operating system entirely based on web technologies. W3C and Intel partnered to create a T-shirt that says “I See HTML5 Everywhere.” And indeed, I do.

The challenge of mobile

Not only has the web a big role to play on mobile, mobile has also a key role to play for the web. As more and more of our connected interactions start or end on mobile devices, we must ensure that the web platform adapts to our mobile lives. I believe this is critical for the future of the web.

For many years W3C has designed technology to make the experience of web users on mobile ever more rich, adapted, and integrated. For example, CSS media queries provide the basis for responsive web design. There is already a lot for mobile, and a lot more is coming. To help people follow all the activity, every quarter I publish an overview of web technologies that are most relevant to mobile.

These technologies are the tools designers can rely on to build the user experience they need. But technologies are only a small piece of the puzzle when it comes to making the web user experience work on mobile devices. The number of A List Apart articles about mobile development provides a clear sign that this challenge is driving creativity in the design community. Responsive web design, mobile first, future friendly, and just-in-time interactions are some of the trends that have resonated with me over the years. The creativity is fantastic, but we still want our lives to be easier. Where web technologies do not yet provide the hooks you need to practice your craft, please let us know. Feel free to write me directly: dom@w3.org.

Closing the gap

Another challenge that we, the web community, face on mobile is the amazing energy devoted to native development.

The web has displaced a lot of the native software development on traditional computers; on mobile, the reverse trend has happened. Content that users had enjoyed on the web for years started to migrate to native applications: newspapers, social networking, media sharing, government services, to name a few. And to add insult to injury, a number of these content providers are pushing their users away from their website toward their native application, with obtrusive banners or pop-ups.

It is unclear where the world is going on mobile: some statistics and reports show a strong push toward moving back to the web (e.g., the recent Kendo UI survey), while others argue the opposite. What is clear to me, though, is that we cannot afford to let mobile become a native-entrenched ecosystem.

What has made the web unique and popular in so many hearts is not the technology (some great, some terrible) nor even the ubiquity (since interoperability can reduce it). I believe the much more fundamental importance of the web comes from its structural openness: anyone can publish the content they see fit and anyone can participate in defining the future of the web as a platform.

Native ecosystems on mobile have historically been very closed ecosystems, under the control of single commercial entities. A world where the majority of our information and infrastructure would be trapped inside these ecosystems is not something we should accept lightly. Mind you, I appreciate the innovations spawned by these platforms, but we need to encourage the cycle where innovations become standards, and those standards prime the platform for the next innovations.

Of course the best way to shift the balance to the web is to make the web the best platform for mobile. Achieving this will require ideas and energy from many people, and web developers and designers play a critical role in shaping the next generation of web user experiences. I am leading a focused effort in W3C to assess what we can and should do to make the web more competitive on mobile, and welcome feedback and ideas on what the missing pieces in the puzzle are.

Beyond mobile

I believe a key part in making the web the “king of mobile” is to realize that mobile devices are a means to an end. In our connected world—computers, phones, tablets, TVs, cars, glasses, watches, refrigerators, lightbulbs, sensors and more to come—mobile phones will most likely remain the hub for while. The only platform that can realistically be made available on all these devices is the web.

We have a unique opportunity to make the Open Web Platform a success. I realize getting it right will not be trivial. Building user experiences that scale from mobile (or watches!) to TV is complex. Building user experiences that adapt to these very different type of interactions will be hard. Matching the needs from users in a growing diversity of contexts will make us cringe. Creating user experiences that abolish the devices barrier (as I explored some months ago) is guaranteed to create more than a few headaches.

But there is unprecedented momentum to create an open platform for the planet. And that has me smiling a lot.

0
Your rating: None