Menu Search
Jump to the content X X
Smashing Conf Barcelona 2016

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

Laying Out A Flexible Future For Web Design With Flexbox

CSS floats and clears define web layout today. Based on principles derived from centuries of print design, they’ve worked well enough — even if, strictly speaking, floats weren’t meant for that purpose. Neither were tables, but that didn’t stop us in the 1990s.

Nevertheless, the future of web layout is bright, thanks to flexbox1. The CSS layout mechanism lets us arrange elements in a truly web-like way. Some elements can be fixed, while others scroll. The order in which they appear can be independent of the source order. And everything can fit a range of screen sizes, from widescreen TVs to smartphones — and even devices as yet unimagined. Browser support is fantastic2 (except you-know-who). Yep, it’s a great time to jump into flexbox if you haven’t done so yet.

But changing our ways isn’t easy. Flexbox has a dizzying array of features, few of which are familiar. It’s a lot to take in. Luckily, for layout purposes, you need to know only a few basics. Let’s take a look at how we could create a basic Gmail-like, flexbox-based interface. If you haven’t explored or fully understood flexbox yet, this piece will revisit and explain a few things that might be confusing at first.

The Flexbox Mindset Link

Flexbox requires a new way of thinking. Instead of arranging items in left-to-right, top-to-bottom rows and columns, we arrange blocks on a line — two lines, in fact, a main axis and a cross axis, the first of which we’ll use today. Think of the main axis as a rope along which boxes (divs or other HTML elements) are strung. The metaphorical rope runs from one end of its container to the other, a taut and invisible axis. This leads to four interesting concepts.

Alignment Link

First, we can slide the “boxes” to one side of the “rope” or the other, center them or distribute them evenly. That means objects can stick to one side of a layout or the other — say, to the left or right edge of the screen, no matter the screen’s width. Even distribution means they will adapt well to any size screen, which is ideal in our multi-screen world3.

Illustration of boxes pushed to the left.
Flexbox allows designers to push HTML elements to either end of the “rope.”

Direction Link

We can also reverse the string, so that boxes run in the opposite direction, without editing the HTML. This is similar to the sort-order technique4 that lets us flip columns around — except the third trait takes that a step further.

Illustration of boxes pushed to the right.
Both the order and position of elements may be flipped.

Orientation Link

Thirdly, we can turn the rope by 90 degrees to dangle from the top of its container, instead of running from side to side. Media queries and flexbox’s ability make it possible to run items — say, a header, article and footer — down a smartphone’s screen but left to right on a desktop computer. What used to be called rows can now run top to bottom or bottom to top with a dash of CSS.

Illustration of boxes hanging from the top of a box.
The entire arrangement can turn 90 degrees, “hanging” from the top of the container.

Order Link

Finally, we can control which boxes come first, second, third and so forth on the rope without editing the HTML. This is huge. It means we can structure an HTML document for, say, SEO5, accessibility6 or plain ol’ semantics7 — independent of layout. Want to center elements vertically? No problem. Want navigation at the end of your HTML but at the beginning of your layout? Sure. Want to experiment with different layouts? It’s all in the CSS. And just like that, we’re already thinking in terms of content and devices, not rigid grids.

Illustration of boxes in random order.
The exact order of elements can change with CSS — and without changing the HTML.

There’s more, but this covers the basics for now. To recap:

  1. Blocks are strung along an invisible line.
  2. We can push them to and fro along that line.
  3. We can reverse the line, thus reversing the boxes’ order.
  4. The line can turn 90 degrees.
  5. We can shuffle things along the line in any order we please, regardless of the HTML.

Order Link

Order is an important concept in flexbox. Let’s take a basic HTML document: A typical blog post would include certain bits of information.

  • header
    website title, description, search form (These frame the content and inform people where they are.)
  • meta data
    author/publisher, date, topic(s) (These help people decide whether the content is relevant to their needs.)
  • main content
    what the page is all about (the reason the page exists)
  • supplemental content
    related information (teasers, links, “See also”)
  • navigation
    links to elsewhere on the website (high-level topics)
  • footer
    copyright, RSS, social media, newsletter registration

These elements are listed in order of what search engines or screen readers might scan. Now, let’s dangle a “rope” from the top of a mobile device and reorder them to put content first.

  1. main content
  2. meta data
  3. supplemental content
  4. header
  5. navigation
  6. footer

Meanwhile, desktop computers would have a different view.

  1. header
  2. meta data
  3. main content
  4. supplemental content
  5. navigation
  6. footer

Wait, that’s not quite right. We want navigation at the top, and flexbox makes that a snap.

It follows that you can also put “ropes” inside of boxes, and all of the rules apply anew. But first, let’s talk about order. Here’s where things get tricky.

Nesting Ropes And Boxes Link

Each flexbox layout — each box — can contain another set of boxes strung along their own rope. That rope can run from left to right or vice versa, from top to bottom or vice versa, and push objects to either end, center them or distribute them. And while that flexibility opens up many possibilities, it also means we need to plan our layouts carefully.

Illustration of boxes within a box.
Elements along a flexbox rope may, in turn, contain other flexbox ropes.

Let’s start with some content to understand why things get complicated; this isn’t necessarily in order of layout (i.e. the order in which people see it). Imagine giving a presentation to an audience. You tell them what you’re going to say, then you say it, and you wrap up with a summary of what you’ve said. Our hypothetical page follows a familiar structure:

  • header
  • the current message
  • message list
  • links to inbox(es), archive, etc.
  • footer

Sketch A Design Link

To keep things simple, we’ll work with a familiar layout.

Illustration of an email app layout
A typical arrangement for an email app.

There are two flexbox layouts here. The first has three boxes from top to bottom. The second layout resides inside the middle box, from right to left.

The header and footer span the width of the viewport. The navigation fits in a small column to the left, and the content area lets the user scroll when it contains more information than can be displayed. We could achieve this with a few floats and fixed positions, but flexbox gives us more options with less markup. Let’s take a look.

Set Up The Document Link

The outer container has only three sections, wrapped in a .flex-container element:

<body>
  <div class="flex-container">
    <header>…</header>
    <main class="flex-container">…</main>
    <footer>…</footer>
  </div>
</body>

We call it flex-container to describe its purpose in a somewhat semantic way. At least our CSS will make sense.

Inside the main element, we need three blocks:

<main class="flex-container content">
  <article class="message">…</article>
  <div class="message-list">…</div>
  <nav class="mailbox-list">…</nav>
</main>

This example uses article as an independent entity, not in the magazine sense8.

Declare These Elements As Flexbox Link

We need to tell browsers that these elements will be, um, flexible.

.flex-container,
.flex-container header,
.flex-container footer {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
}

Note that this applies flexbox to the major containers, not the content.

Add Some Dimensions Link

Based on the design sketch, we know that certain elements will have widths and heights. The body’s header and footer, for example, will be long, thin strips compared to the main’s tall, relatively narrow left-hand navigation bars. The article’s content area fills the rest of the space. In the interest of staying flexible regardless of screen size (and clarity in this tutorial), these areas won’t have fixed widths.

.message {
  flex-basis: 70%;
}
.message-list {
  flex-basis: 15%;
}
.mailbox-list {
  flex-basis: 15%;
}
.flex-container header,
.flex-container footer {
  width: 100%;
  height: 5rem;
}

Here, flex-basis is like width — as long as the main axis is horizontal. If we dangle the rope from the top, then flex-basis becomes height automatically. Handy!

Make The Main Section Scrollable Link

This one’s easy. Just add overflow: scroll to the main element to keep it from overriding the header and footer. Handy tip: Try overflow: auto to hide scroll bars (when they’re unnecessary) in most browsers9.

.message {
  flex-basis: 70%;
  overflow: scroll;
}

Test The Content Link

At this point, the header’s form should float with a little margin, even when the browser is resized. The content should flow well in browser windows of any size. And if a browser doesn’t support flexbox, then the page will turn into a content-first layout.

That’s important because you-know-who doesn’t support flexbox10 yet. Every modern version does, however, so it’s a matter of when users update their software. So, where is flexbox supported?

Clicky has a graph of the marketshare of assorted mobile browsers.15

What about older browsers? Solutions vary wildly depending on the layout you’re trying to achieve, although we can derive a few tips.

The safest way to support flexbox-incapable browsers is to write CSS in the order in which you want it to appear. Start by thinking semantically16. Old versions of Internet Explorer will ignore flexbox properties — thankfully, good ol’ conditional comments17 enable us to apply floats and clears to semantic layouts. Old versions of other browsers tend to give you mobile-friendly layouts that stack content in a logical order. So flexbox can co-exist with floats, display: table-cell and positioning, so that smart browsers will apply flexbox properties while legacy browsers will ignore them. Finally, if you’re feeling experimental, then try Flexie18, which amends old browsers with a JavaScript-based polyfill.

Give flexbox a go. While it offers many options, most — such as alignment — come into play after you’ve settled on how elements are arranged. The central techniques, which we’ve covered here, are alignment, direction, orientation, order and nesting. We’ve found these to be critical in Foundation’s new layout framework: If you can wrap your head around alignment, direction, orientation and order, then you’re well on your way to a flexible future. Check out my demo19 to see it in action (keep in mind that it’s not responsive just yet).

Further Reading Link

To learn more about flexbox, check out the following:

(da, ml, al)

Footnotes Link

  1. 1 https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes/
  2. 2 http://caniuse.com/#search=flexbox
  3. 3 https://www.smashingmagazine.com/2011/01/12/guidelines-for-responsive-web-design/
  4. 4 http://foundation.zurb.com/docs/components/grid.html#source-ordering
  5. 5 https://www.smashingmagazine.com/2013/11/15/seo-for-responsive-websites/
  6. 6 http://zurb.com/university/lessons/five-minutes-towards-an-accessible-page
  7. 7 http://html5doctor.com/lets-talk-about-semantics/
  8. 8 http://html5doctor.com/lets-talk-about-semantics/#what-about-adding-more-elements
  9. 9 http://caniuse.com/#search=overflow
  10. 10 http://caniuse.com/#search=flexbox
  11. 11 https://clicky.com/marketshare/global/web-browsers/google-chrome/
  12. 12 https://clicky.com/marketshare/global/web-browsers/firefox/
  13. 13 https://clicky.com/marketshare/global/web-browsers/internet-explorer/
  14. 14 https://clicky.com/marketshare/global/web-browsers/safari/
  15. 15 https://clicky.com/marketshare/global/web-browsers/mobile/
  16. 16 https://www.smashingmagazine.com/2013/08/20/semantic-css-with-intelligent-selectors/
  17. 17 http://www.quirksmode.org/css/condcom.html
  18. 18 http://flexiejs.com
  19. 19 http://codepen.io/benthinkin/pen/wadabR
  20. 20 https://github.com/philipwalton/flexbugs
  21. 21 http://the-echoplex.net/flexyboxes/
  22. 22 https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_flexbox_to_lay_out_web_applications
  23. 23 http://tympanus.net/codrops/css_reference/flexbox/
  24. 24 https://scotch.io/tutorials/a-visual-guide-to-css3-flexbox-properties
  25. 25 http://dev.w3.org/csswg/css-flexbox-1/
SmashingConf Barcelona 2016

Hold on, Tiger! Thank you for reading the article. Did you know that we also publish printed books and run friendly conferences – crafted for pros like you? Like SmashingConf Barcelona, on October 25–26, with smart design patterns and front-end techniques.

↑ Back to top Tweet itShare on Facebook

Advertisement

Ben Gremillion is a Writer at ZURB. He started his career in newspaper and magazine design, saw a digital future, and learned HTML in short order. He writes tutorials and facilitates the ZURB University training courses.

  1. 1

    Rafael Corrêa Gomes

    August 17, 2015 5:18 pm

    I had planned to use , but it started when I read this post. Congratulations, very good!

    4
  2. 2

    Fantastic article – I really like these visuals for explaining the Axis.

    I recently released a free video course on Flexbox → http://flexbox.io

    13
  3. 4

    Great article!

    0
  4. 5

    This really cleared up flexbox for me. Thanks.

    1
  5. 6

    Flexbox is great but be careful when using it as primary layout mechanism in non-SPA pages:

    https://jakearchibald.com/2014/dont-use-flexbox-for-page-layout/

    The problem is the entire page has to be loaded before the dimensions of the layout are finalized. This means your layout can have “seizures” as your sidebars load. This is a really poor experience for someone trying to read your article…

    -1
  6. 7

    Thanks for the article. Very well written.
    If you plan on writing a follow up article it would be great to see some creative and advanced layout examples using distribution, alignment, nesting and other flex box features.

    3
  7. 8

    Andy Mehalick

    August 18, 2015 7:08 am

    Great article but your readers will need to set flex-direction if they want to approximate your sketch:

    div.flex-container {
    flex-direction: column;
    }

    main.flex-container {
    flex-direction: row-reverse;
    }

    The default direction when not specified appears to be flex-direction: row which doesn’t stack header/main/footer.

    http://codepen.io/anon/pen/oXREoY

    5
    • 9

      Good point, Andy. Thanks for showing us with a pen.

      0
      • 10

        Ben thank you for the easy to understand analogy, but consider updating your article. I worked out your example in Codepen as I read your article, and at first was confused by the result and assumed it was me, but then I discovered that you simply didn’t cover all the bases and felt frustrated.

        (Thanks Andy for clarifying.)

        2
        • 11

          I agree… I thinks it’s a bit baffling that someone writing an article in Smashing Magazine wouldn’t take the time to actually test the code they’re sharing. I’m familiar with flexbox, but it took me a couple of minutes and frowning because I couldn’t believe there was missing declarations and that is must’ve been because there was something I wasn’t getting…

          1
  8. 12

    Thanks for a great and useful article!

    0
  9. 13

    Dimitar Stojanov

    August 18, 2015 8:35 am

    Hey Ben, nice explanation! And thanks for linking my Scotch.io tutorial “A Visual Guide to CSS3 Flexbox Properties”!

    3
    • 14

      My pleasure — and thank *you* for sharing such a useful resource with the design community.

      1
  10. 15

    Flexbox is awesome – I use it a lot where appropriate. But it’s not ideal for a full page layout.

    It’s awesome for components such as headers, footers, menus etc.

    0
    • 16

      Depends on the page. I believe that web apps’ views will find this very handy, and that websites will become more app-like in the future. Only time will tell if I’m right.

      1
  11. 17

    Great & useful article.

    1
  12. 18

    I have a question. Have anyone problems with performance during using deeply nested flexboxes? Firefox in my case is not smooth.

    1
    • 19

      Flexbox is still relatively new. Browser support (read: better handling of new techniques) should improve over time.

      2
  13. 20

    A little unfair to implicitly call out Internet Explorer on flexbox support. It’s fully supported in IE11 (albeit with a couple of quirks, e.g. with pixel rounding), which is available to everyone using Windows 7 and above. Given that Windows XP is no longer supported, that only leaves Vista, which is not widely used. And it doesn’t require a prefix, unlike Safari, so that cheap shot is a little outdated in my view.

    -3
    • 21

      Fair point, Noelinho. When I began researching the article, IE’s support was questionable. Maybe I didn’t take later versions into account enough. Good to know that it doesn’t require vendor prefixes. Still, it requires a few workarounds … for now.

      1
  14. 22

    Good stuff, now I will refer to it.
    Thanks for a nice and coolest article!

    -1
  15. 23

    The example code doesn’t create the layout at all like described. Here’s the code on CodePen:

    http://codepen.io/anon/pen/GJaBwL

    -1
    • 24

      Dan, the ellipses in the example HTML are meant to be replaced with your own content. :)

      -1
  16. 25

    You can actually accomplish the same layout using only one flex container and flex-flow set as row e.g.
    http://codepen.io/anon/pen/aOrjaE

    (borrowed from https://css-tricks.com/snippets/css/a-guide-to-flexbox/)

    2
  17. 26

    I’ve been using Flexbox for some time now, mostly in combination with Bootstrap. While this will definitely be the future of creating layouts I still think it’s too soon to use it fully, most notably due to backwards browser support concerning IE. Sometimes I still get requests for IE 8 compatibility so it will probably still be years before we can fully incorporate Flexbox.

    3
  18. 27

    IPacktechnologies

    August 19, 2015 1:35 pm

    Great article on Flex box. It’s very helpful in CSS layout. Thanks!

    0
  19. 28

    For reference Flexie was for an outdated spec, it’s not had any work done in 4 years and is incompatible with the current flexbox spec.

    0
  20. 29

    Interesting approach to responsive design !!!!

    0

↑ Back to top