HTML & CSS - - By Bashkim Isai

Migrating to Flexbox by Cutting the Mustard

As front-end developers, the time has come to move away from using CSS floats and dive into the new and exciting world of flexbox. CSS floats are a dated approach to styling layouts; they have been available in Internet Explorer since version 4.0 and workarounds are required to make them malleable (including the clearfix hack and using the nth-child pseudo-class for wrapping columns).

The main topic of this article is how to implement flexbox across multiple browsers considering its fragmentation. If you want to become more familiar with flexbox, there are many good resources available, and I highly recommend the following:

By the end of this article, you should be able to:

  • Understand which versions of flexbox to target for a responsive website.
  • Utilise flexbox via feature detection (cutting the mustard) and provide a fallback for legacy browsers.
  • Move away from using IE conditional comments in most situations.
  • Demonstrate a practical use for flexbox by creating a basic 2×2 grid with a legacy fallback.

A Brief History of Flexbox

The Flexible Box Layout Module (a.k.a. flexbox) is a new way of structuring layouts in CSS. It has undergone multiple revisions and has evolved significantly in its relatively short existence. At the time of writing flexbox is still a W3C working draft, but, like other standards, that shouldn’t make it unappealing in a production environment.

There are three iterations of the standard, commonly referred to as the old syntax, the tweener syntax and the new syntax.

The limitations of flexbox are well documented:

  • The old syntax does not support flex-wrap.
  • The tweener syntax is only supported in IE 10 (including mobile).
  • The new syntax is not fully implemented in Firefox (22-27) as it is missing the flex-wrap and flex-flow properties.

Wrapping (flex-wrap) is an important feature of the specification, which is required to create a responsive grid. For this reason, it’s best to target only the tweener syntax and browser versions that fully implement the new syntax.

This leaves us with the following browser versions:

  • Internet Explorer 10 (tweener syntax with the -ms- prefix)
  • Internet Explorer 11 and Edge (new syntax)
  • Firefox 28+ (new syntax)
  • Chrome 21-28 (new syntax with the -webkit- prefix)
  • Chrome 29+ (new syntax)
  • Safari 6.1+ (new syntax with the -webkit- prefix)
  • iOS Safari 7.0+ (new syntax with the -webkit- prefix)

As there are browsers with a significant market share that do not support flexbox, these should fallback to using CSS floats. But how can this be expressed in code? What’s the best way to differentiate between browser versions that should receive CSS with floats instead of flexbox? What strategy can be used to ensure versions of Firefox that support the new syntax but don’t support wrapping are identified as legacy?

Introducing: Cutting the mustard.

Cutting the Mustard (Feature Detection)

If you haven’t heard it as a technical term before, “Cutting the mustard” was coined by the development team at BBC News. The term stemmed from the fact that the BBC website must cater to a vast international audience and targeting browser versions and devices specifically would have been a cumbersome solution.

The crux of the concept is identifying which browser/device/user agent is being used and serving polyfills to get the site to work. The existence of specific features is detected on the client side and therefore the most appropriate solution for the available technology is delivered.

Feature detection is not new. The aforementioned BBC article was published in March 2012 and while it has grown in popularity, it’s surprising to see websites still implementing IE-specific conditional classes as popularised by Paul Irish in 2008.

Modernizr (contributed to by Paul Irish) is all about feature detection:

Taking advantage of cool new web technologies is great fun, until you have to support browsers that lag behind. Modernizr makes it easy for you to write conditional JavaScript and CSS to handle each situation, whether a browser supports a feature or not. It’s perfect for doing progressive enhancement easily.

Although CSS now has native feature detection, it currently does not have enough market share to be viable for real-world use. The remainder of this article will discuss how to ditch the IE conditional comments in favour of feature detection in JavaScript.

Identifying Features and Browsers

Every project requires a different set of features in order to function. There are multiple ways feature detection can be realised, the easiest of which includes:

The most efficient approach is the vanilla JavaScript implementation. It’s fast (as it doesn’t require the client to download any additional libraries) and does not require any additional processing. This approach is far from perfect as there are known issues; however there are ways to overcome common feature detection problems.

[B]rowser detection has become an impossible tangle, and has largely fallen out of use, to be superseded by something far better — feature detection.

[…] feature detection isn’t completely reliable either — there are times where it fails.

James Edwards

Choosing Modernizr for cutting the mustard may not be as efficient (as it requires downloading and client processing), but manually detecting flex-wrap support is not a straightforward task. It’s also important to note that although Modernizr version 2 doesn’t detect flex-wrap, version 3 does! The feature is labelled as Flex Line Wrapping.

Although the option exists to use the CSS classes attached to the document root produced by Modernizr (e.g.: html.flexwrap), it’s better to serve separate CSS files for each experience to reduce the download size of the site.

The BBC News developers refer to two types of browsers:

Someone on the team started referring to them as “HTML4 browsers” and “HTML5 browsers”, which we find is easier to communicate the sentiment to non-technical people.

BBC Responsive News

This rationale was perfectly valid when you consider the climate of the browser landscape in 2012; however as new features become available, the division is not necessarily as clear. Flexbox, for example, isn’t fully supported in all “HTML5” browsers.

A robust approach is to differentiate between “legacy” and “modern” browser versions. In addition, some projects may require multiple divisions where half-way (or “transitional”) browsers can be identified.

Implementing the Approach

Start by creating the following files:

  • index.html – the main HTML file
  • stylesheets/modern.css – styles for modern browsers (media queries, flexbox with wrapping)
  • stylesheets/legacy.css – styles for legacy browsers (no media queries, no flexbox)
  • scripts/dependencies.js – performs feature detection

Here’s how our index.html file will look:

<!DOCTYPE html>
<html class="no-js">
  <head>
    <title>Cutting the mustard</title>
    <script src="javascripts/dependencies.js"></script>
    <noscript>
    <link rel="stylesheet" href="stylesheets/legacy.css">
    </noscript>
    <!-- ... -->
  </head>
  <body>
    <div class="container">
      <div class="cell cell-1">Cell 1</div>
      <div class="cell cell-2">Cell 2</div>
      <div class="cell cell-3">Cell 3</div>
      <div class="cell cell-4">Cell 4</div>
    </div>
  </body>
</html>

Notice that there are no IE conditional comments? Just clean and valid HTML code. And if the browser does not have JavaScript enabled, it will fall back to using legacy.css regardless of its level of support.

You may also notice that the script tags are at the top of the HTML page. This is because Modernizr should process and inject the stylesheets before the browser paints for the first time. This reduces repaint and helps to avoid a Flash Of Unstyled Content (FOUC). But remember that most script tags would be at the bottom of the page.

Our legacy.css file will contain the following:

.container {
}

/* clearfix */
.container:after {
  content: "";
  display: table;
  clear: both;
}

.cell {
  width: 50%;
  float: left;
}

/* wrapping */
.cell:nth-child(2n+1) {
  clear: left;
}

/* for visiblity */
.cell-1 { background-color: #000; color: #fff; }
.cell-2 { background-color: #666; color: #fff; }
.cell-3 { background-color: #ccc; color: #000; }
.cell-4 { background-color: #fff; color: #000; }

This implementation includes a clearfix hack and the :nth-child pseudo-class for wrapping. It works in most browsers; however Internet Explorer 8 requires Selectivizr or an equivalent solution to get the selector working.

Next, our modern.css file:

.container {
  /* Internet Explorer 10
   */
  display: -ms-flexbox;
  -ms-flex-wrap: wrap;

  /* Chrome 21-28
   * Safari 6.1+
   * Opera 15-16
   * iOS 7.0+
   */
  display: -webkit-flex;
  -webkit-flex-wrap: wrap;

  /* Chrome 29+
   * Firefox 28+
   * Internet Explorer 11+
   * Opera 12.1 & 17+
   * Android 4.4+
   */
  display: flex;
  flex-wrap: wrap;
}

.cell {
  -webkit-flex: 1 0 50%;
      -ms-flex: 1 0 50%;
          flex: 1 0 50%;
}

/* for visiblity */
.cell-1 { background-color: #000; color: #fff; }
.cell-2 { background-color: #666; color: #fff; }
.cell-3 { background-color: #ccc; color: #000; }
.cell-4 { background-color: #fff; color: #000; }

Don’t be put off by the size of this file. The comments make it appear larger, but these make it easier in development to understand what each section is targeting.

Next we will write the code for dependencies.js.

As mentioned, we need to generate a version of Modernizr (version 3) which detects the support of the flex-wrap property. Include the code at the top of the JavaScript file.

/* Include Modernizr v3 with 'Flex line wrapping' here */

(function() {
  var isModern = Modernizr.flexwrap;

  var link = document.createElement('link');
  link.rel = 'stylesheet';
  link.type = 'text/css';
  link.href = 'stylesheets/' + (isModern ? 'modern' : 'legacy') + '.css';

  document.getElementsByTagName('head')[0].appendChild(link);
})();

You can optionally increase the requirements for a modern experience by adding to the isModern Boolean. For example:

var isModern = Modernizr.flexwrap && 'querySelector' in document;

Sass Solutions

You can use Sass to abstract your approach to implementing flexbox. This reduces the size of the CSS output and makes it easier to maintain:

%flexbox {
  display: -ms-flexbox;
  -ms-flex-wrap: wrap;
  display: -webkit-flex;
  -webkit-flex-wrap: wrap;
  display: flex;
  flex-wrap: wrap;
}

.container1 {
  @extend %flexbox;
}

.container2 {
  @extend %flexbox;
}

Progressive Enhancement and Browser Testing

It’s important to understand the differences between flexbox and CSS floats. Your implementation will not look exactly the same in each of the experiences — but the notion of progressive enhancement means that it doesn’t necessarily have to.

For example, by default, flexbox will stretch all cells on the same row to have the same height. Therefore, if one cell is 3 lines long and the adjacent row is 10 lines long, the background will stretch on both cells to 10 lines. The fallback for CSS floats will not do this and both cells will have uneven heights.

Testing the layout in multiple browsers is still a requirement, but remember that forcing the value of isModern to false in JavaScript can help test legacy solutions in any browser:

var isModern = false; // Modernizr.flexwrap;

Conclusion

In this article, I’ve provided the basics for using feature detection to serve two different stylesheets on the same HTML code base. This is an extremely effective way of beginning the upgrade process away from CSS floats and reducing the dependency on IE conditional comments.

Although there has been a strong focus on detecting support for flexbox, it’s important to note that as new features are developed for browsers, this approach to cutting the mustard can be adapted and evolved to suit future requirements.

Once Internet Explorer 10 falls out of popularity with the browser market share in your target sector, you may be able to ditch the tweener syntax and deliver leaner code solely through the use of the new syntax.

So now that you have all of the theory, why not get well acquainted with flexbox in your next project?

Sponsors