The CoffeeCup Guide to

DESIGNING WITH FLEXBOX in Foundation 6

Author

Bob V.
CoffeeCup Chief

Design

Diego N.
CoffeeCup Designer

Production Rights

© CoffeeCup Software
www.coffeecup.com

Flexbox is a CSS3 module for managing the distribution of space, and the positioning of elements, across the wide variety of screen sizes.

Many layout designs that were difficult or impractical to create with CSS ‘sans-flexbox’, are are now easy to achieve. Vertically aligning or evenly spacing out elements are good examples.

For responsive designs, the flexbox possibilities are amazing.

For responsive designs, the possibilities are even cooler. Changing the order of elements for larger (or smaller) screens, for example, is simply a matter of changing the values, e.g. from  4 to  1 , for the order property! In short, flexbox allows us to easily manipulate the layout for an entire series of elements.

Foundation 6 is the popular and powerful front-end framework developed by the great people of Zurb (and community). It provides proven methods for creating components such as accordions, modals and dropdowns as well as a responsive grid system.

Foundation 6, Flexbox and Foundation Framer

In this guide we will go over the flexbox syntax and look at the visual effects that can be created with them. The guide and flexbox design cases have been created with Foundation 6 using Foundation Framer. Framer provides a visual layer for working with the framework (and flexbox).

With Framer no coding is needed, speeding up the learning experience, as well as the prototyping and design processes. You don't have to use Framer to benefit from this guide, but it certainly won't hurt to give the app a try!

About this guide

In this guide we will go over the flexbox syntax and look at the visual effects that can be created with them. Also included are numerous practical examples and showcases of layout configurations made with flexbox.

To get the most out of this guide you should consider interacting with the designs. This can be done using the Inspector in the browser, or with Foundation Framer.

Download the interactive version

The visual tools of Framer make it easy to cycle through the different flexbox settings, seeing the impact at the same time. A free (trial) copy of the app with this guide preloaded can be downloaded with the buttons below.

With that behind us, let’s dive deep into this box of layout freedom!

00

Table of Contents

New found layout control

We touched upon a couple of the possibilities flexbox has to offer in the introduction above. The relatively easy to understand syntax provides a tremendous amount of layout control. There are a number of online resources available that discuss the different flexbox properties and their values.

However, there are very few practical demonstrations that showcase real design examples. And as we all know, making something for production can differ significantly from showing something in an isolated setting. When using the flexbox syntax in isolation, potential conflicts with other properties are left out of the picture. An example would be using flexbox centering, together with specific margin settings for elements — in that case flexbox might seem to not exactly work as expected.

So let's get warmed up for this cool (and finally widely supported CSS3 module), and kick-off with a real life design example.

In the design below most of the layout configuration is handled by flexbox. The logo and navigation container, seen below the 640px breakpoint, are stacked. While at wider screens, they are nicely spaced out in the header without using complicated floats, inline-blocks or endless margin tweaks.

The same is true for the navigation links. With flexbox, it takes just a few clicks to to center them in their container on small screens, and then place them on the right (flex-end) above the 640px breakpoint.

Making something for production can differ significantly from showing something in an isolated setting.

The action items (newsletter subscribe request) are placed exactly in the middle of the area below the header. Both horizontally and vertically, something that would impose a serious challenge without the help of flexbox.

Catch the vibe. Subscribe to our newsletter.

The cool thing is that if you're viewing this example inside of Foundation Framer, you can easily play with the flex property values and see how the elements behave. Go ahead, click on the picture above to select the flex parent container. Then, on the Design pane, scroll down to the position section. The flex controls are located right below the display drop down.

You’ll see that changing the flex-direction is pretty intuitive. Depending on the value, the elements are stacked as a column or displayed inline as a row. Changing the justify-content drop down influences the position of the elements in the flex column or row. Now don’t go too wild immediately! Using flexbox is way more fun with a better understanding of the mechanics.

Please note that the example above would have been even simpler if Internet Explorer 11 would be taken out of the picture. Although it is a major improvement over IE 8, 9 & 10 (for which Microsoft stopped support in January 2016) and offers good overall Flexbox support, it does suffer from a few Flexbugs. One of them relates to the use of min-height. In order for flex elements to position themselves, they need to know about the dimensions of the parent. Whenever a minimum height is used, the flex elements seem to get confused and act as if no height has been set at all. Luckily there are workarounds.

In the example above we use double nesting, placing a container in a column, to fix issues. The subscribe input field and button are then placed in a grid container to position them with  flex . The wonderous Philip Walton did a great job documenting Flexbugs and workarounds. Some of them will pop up below. Ready for the good news? The next version of Internet Explorer (which Microsoft labelled 'Edge’) solves about all of them! Yep, the future of Flexbox looks bright indeed.

When to use flexbox

As mentioned in the introduction, the current best practice is to use flexbox for subsets of the layout, not for constructing a complex, grid-based full page layout. One of the main reasons is that for large pages and/or slow connections, the layout can shift around during page loading.

It is also not clear from the official specification if flexbox was indeed intended for that type of usage. In fact, considering that the CSS Grid Layout workgroup includes several of the same Editors, it seems more likely that the flexbox layout module was designed to address specific layout problems within parts of the overall layout, rather than to create a layout module for page or grid construction.

Don’t take me wrong, flexbox is one of the most versatile and intuitive layout systems. However, it performs best when set to a specific purpose like, for example, aligning a series of items within a container. It’s also great for changing the layout direction — from column for small screen to row for wider screens, for maintaining height, updating the visual order of elements and a bunch of other use cases that we will go over in this guide.

Flexbox is one of the most versatile and intuitive layout systems.

Time to set up the initial flex layout, following which we can get to work on some fun demos and use cases!

Setting up the flex layout

A flex layout is created by setting the display property of a container element to flex. This can be any element that contains other elements, from a simple column or container, to a list container. The container can be any type of HTML container, a simple <div> or a more semantically labelled element such as a <section> or <nav>. When the flex display value is used, the parent container becomes a flex-container, and all immediate children become flex-items.

Responsive design is a requirement and height changes are very common in a multi-device world.

The main characteristic of the flex container is the ability to modify the order, position, alignment, width or height of its children. This allows the designer to use the available space in the best possible way.

As we saw in the example above, even symmetrical perfection can be achieved. True, before flexbox we were able to use margin or padding to vertically center elements within a section. Or at least approach it for a static layout. But keeping multiple elements aligned is a big endeavour, especially if they are not the exact same size.

In addition, we’re living in a multi-device world where responsive design is a requirement and height changes are very common — due to, for example, wrapping text. As soon as that happens we would be entering the trouble zone, chasing height using breakpoints without a real solution to the problem.

In short, cleverly positioning elements within a container is both more powerful and less complicated with flexbox. There are five properties for the flex-container that can be used to influence the way the flex-items are laid out.

Manipulating the flex layout

Want to play with flexbox in Foundation Framer? Download a trial version here.

The flex-direction property is used to define the direction the flex-items follow in the flex container. The initial function is to tell the flex-items to position as (horizontal) rows or (vertical) columns.

Placeholder Picture

The 4 flex-direction values.

In addition they can be instructed to change their natural order and reverse their position from right-to-left or bottom-to-top.

flex-direction

The design example below illustrates the directional behavior. I dropped three containers in the (single column) of a full-width row. The normal behavior of these block elements would be to stack vertically, but choosing display  flex  for the column and setting the flex-direction to  row  places them nicely next to each other.

In Foundation Framer, double-clicking the column in the example below will bring up the Design pane. The settings can be seen (and changed) by scrolling down to the Position section. They are visible in the screenshot as well.

Placeholder Picture
FLEX-ITEM-1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas et metus.

Placeholder Picture
FLEX-ITEM-2

Quisque eleifend gravida libero, vitae ultricies augue blandit vel. Mauris dictum purus in dictum ultrices. Integer id odio ac erat sagittis mattis non at nunc.

Placeholder Picture
FLEX-ITEM-3

Phasellus consequat, sapien id varius fermentum, justo erat ultricies ante, sed aliquet justo quam eget mi.

Using a width of  100%   these containers would try to take up all the space they can get. However, flexbox tells them to split the available space in 3 (or in whatever number of elements would be placed there) so they fit next to each other.

Want to display the items in a different order? That’s no problem when using flexbox. Simply set the flex-direction to  reversed-row   and you’ll get the result you see below.

The white containers are not only flex-items, they are flex-containers too because they also use the flex display property for arranging the elements inside. For these three flex-containers we are using a different flex-direction:  column . The align-items property is used to horizontally center the items within the container.

Placeholder Picture

Flex settings for the white containers.

What's up with these blue lines!?

It's part of the color coding system that makes working with CSS selectors easy in Foundation Framer. A good understanding of selectors makes working with CSS a breeze, you can read all about it here.

Placeholder Picture
FLEX-ITEM-1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas et metus.

Placeholder Picture
FLEX-ITEM-2

Quisque eleifend gravida libero, vitae ultricies augue blandit vel. Mauris dictum purus in dictum ultrices. Integer id odio ac erat sagittis mattis non at nunc.

Placeholder Picture
FLEX-ITEM-3

Phasellus consequat, sapien id varius fermentum, justo erat ultricies ante, sed aliquet justo quam eget mi.

The elements inside the container get some extra styles. If you using the slider, you'll notice the paragraphs are hidden when viewed below the (custom) 310px breakpoint. This is done in the design pane by setting the display control to none. At larger screen sizes, to make them come back into view, the display is set to block.

I also added a max-width to the paragraphs. This prevents them from endlessly expanding with the (white) containers at wide screens. This also helps to battle a bug in IE where paragraph text in a flex-container does not wrap.

Please follow the examples at widths over 310px.

All the examples are left intact as much as possible — the CSS specification keep corresponding with the explanatory text — at all screen widths. However, below 310px flex items positioned as rows became really crammed.  There I added a custom (non-foundation) breakpoint and allowed the items to wrap.

Some items maybe hidden may be hidden as well. To see and edit hidden items, click on the Inspector pane to view the DOM tree. From there, a list of all the rows, columns, and elements will be listed in order as they appear on the design. 

Hidden items will have a small eye graphic next to it. Click on that icon to bring the individual item into view. Alternatively, you can check the box that says "show all hidden items" to make the hidden elements visible.

A real flexbox design case

The project design went really smooth up until now. And that’s exactly how it is for demos that explain how flexbox works in isolated settings using stable, single-size, placeholders.

But we’re dealing with a real design case here — we’re using real elements, combinations of elements, and the paragraphs have different text lengths. The design still has to look good, and that’s how we find how flexbox really works!

Let’s look a bit deeper into the width settings for the container elements. Giving them a width of 100% and using the flexbox settings as explained above, gives each of them an equal amount of the available space. But if we change the width to  auto , the width of each container suddenly varies. The amount of text now determines how much space a container takes up. With the exact same content, they all get the exact same width, but that almost never happens in a real design.

So things do change when different content like, for example, different paragraph lengths, is used in the same type of container: the flex-item is automatically sized based on the its content. Please note that in order to demonstrate this behavior, the max-width had to be removed from the paragraph. That also means that if you’re reading this in IE, the bug I referenced above will pop up causing the text to overlap.

Now, is this behavior desirable? Looking at the example below on a screen wider than 1050px, this can definitely be neat. However, with the different container sizes the images will resize differently at smaller widths. And although the containers maintain the same height when that happens, the horizontal alignment of the content is not maintained. A likely undesirable consequence in most real-world designs.

Placeholder Picture
FLEX-ITEM-1

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas et metus.

Placeholder Picture
FLEX-ITEM-2

Quisque eleifend gravida libero, vitae ultricies augue blandit vel. Mauris dictum purus in dictum ultrices. Integer id odio ac erat sagittis mattis non at nunc.

Placeholder Picture
FLEX-ITEM-3

Phasellus consequat, sapien id varius fermentum, justo erat ultricies ante, sed aliquet justo quam eget mi.

The examples we've seen really do illustrate the powerful layout design possibilities flexbox offers. Independent of  container or element size, flex-items can be placed on a single line. This default behavior, always fitting all items onto one line can be influenced as well. That’s where the flex-wrap property comes into play.

flex-wrap

The flex-wrap property can be used to position a series of items on a single, or on multiple lines. If there is not enough space available for the natural size of the elements, setting this property to  wrap   will place items that do not fit on the next line.

The flex-container below contains two blockquote elements. (Yep, they are perfectly vertically aligned, but that is something we will talk about related to other flex properties.) The point here is that when using  wrap   (with  no-wrap   being the default) as value for the flex-wrap property, these quotes will stack instead of shrink when there’s not enough room in the container to display them next to each other.

If you’re following along within Foundation Framer this is easy to test: select one of quotes and on the design pane, increase the max-width to   500px . With the column never being wider than 1000px this will make them stack.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer posuere erat a ante."
"LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT. INTEGER POSUERE ERAT A ANTE LOREM IPSUM DOLOR SIT AMET, CONSECTETUR POSUERE ERAT A ANTE."

Using the width slider and decreasing the viewport width to below about 1050px will have the same effect. If you’re reading this in a browser you can squish the windows to make them stack, or expand the browser to see the blocks inline.

Natural sizes come in many forms

Both the width of an element and the available space are influenced by many parameters. Widths, heights, max-widths, paddings, and margins, they all play a role. As does the content itself.

If the width is defined in pixels, all is clear. However, in a responsive design widths are often relative, frequently including a width defined beyond which the element should not grow anymore. One would expect the browser to use the max-width value as the ‘maximum natural size’ and most of them do. This time it is Safari, or more precisely the WebKit rendering engine, that presents us with some unexpected behavior.

Whenever a width has been defined for a flex-item, WebKit uses it for calculating the remaining available space, ignoring any maximum width that may have been applied. An element with a 100% width and max-width of 400px will never be wider than the specified 400px pixel size. Still WebKit will take the 100%, inadvertently concluding that no space is available and stack the elements.

The work around? Not specifying a width! Using width: auto  will do wonders. And if automatic resizing based on the content is not desirable, the max-width property can be used to restrain the content inside of the flex-item. Something that is needed on paragraphs to make IE behave anyway. Using the flex-basis property could be another option for preventing the resizing, we’ll look into that later. First let’s see what options we have to distribute the flex-items over the horizontal or vertical space.

justify-content

This property can be used to distribute the flex-items over the space defined in the flex-direction. If the flex-direction is set to  row , the justify-content control determines how the elements are spaced out horizontally.

Similarly, when the flex-direction is used to create columns, this property determines how the elements are spaced out vertically.

Let’s add some fresh images and see how the different values influence the positioning of the three containers. To better illustrate this (and save some room) I constrained their width to 180px . The elements — picture and header — are smaller as well. The paragraph has been removed.

The default value for the justify-content property is   flex-start . The first example shows this, the items are stacked towards the side where the flex-direction starts. As is seen on the second example, when the flex-direction changes, so will the position where the items start.

In Foundation Framer, use the slider to adjust the viewport size, make sure it is on the right of the 640px breakpoint, to see how the elements position based on the justification property.

Row: Flex-start
Placeholder Picture
FLEX-ITEM-1
Placeholder Picture
FLEX-ITEM-2
Placeholder Picture
FLEX-ITEM-3
Reversed-row: Flex-start
Placeholder Picture
FLEX-ITEM-1
Placeholder Picture
FLEX-ITEM-2
Placeholder Picture
FLEX-ITEM-3

The opposite of the default value is  flex-end  You can easily imagine how that will work, or change the value for the design example above.

Placeholder Picture

The 5 justify-content value options.

There are three other values for this property. The  center  value centers the flex-items along the axis of the flex-direction. Elements can also be evenly distributed across the available space using  space-between . The first item is placed where it would be originally when using flex-start. The last item is placed at the end of the axis and all other items are positioned evenly in-between.

Please note that this example can not be illustrated on smaller screens.

There’s simply not enough space remaining. Expanding the viewport will give you the desired effect. Also, since this (and some other) examples need to illustrate specific flexbox settings, I am not updating the design at breakpoints.

Normally the flex-items would probably stack on small screens and be positioned horizontally on wider screens. As mentioned before, that could really confuse people following along on, for example, a phone.

The  space-around  value creates equal space around the elements. Since there's equal space on both sides of the flex-items, the first and last item will be closer to the container edges than the items are to each other.

The three examples below illustrate this using the  row   value as flex-direction.

Row: Center
Placeholder Picture
FLEX-ITEM-1
Placeholder Picture
FLEX-ITEM-2
Placeholder Picture
FLEX-ITEM-3
Row: Space-between
Placeholder Picture
FLEX-ITEM-1
Placeholder Picture
FLEX-ITEM-2
Placeholder Picture
FLEX-ITEM-3
Row: Space-around
Placeholder Picture
FLEX-ITEM-1
Placeholder Picture
FLEX-ITEM-2
Placeholder Picture
FLEX-ITEM-3

No more chasing heights thanks to stretching containers. Yay!

align-items

This property is used for aligning the flex-items on the cross axis of the defined direction. It’s very similar to justify-content but works on the perpendicular direction. Continuing with our example where we use row as flex-direction, we can influence the vertical alignment of the three containers with this property. In order to show this we’ll have to make them different in height first.

To accomplish this for our example, I used a max-width on the pictures in the first and last containers. Without flexbox this would make these white containers shrink as the height is usually determined by its contents. In this case, with the default value  stretch  for the align-items property, the containers will keep filling the vertical space created by the larger middle container. A really handy feature indeed, thanks flexbox!

Align-items: stretch
Placeholder Picture
FLEX-ITEM-1
Placeholder Picture
FLEX-ITEM-2
Placeholder Picture
FLEX-ITEM-3

The second and third example show what happens when the value is changed to  flex-start  and  flex-end  respectively.

The containers stop stretching. They take the height of their contents, and position themselves in the remaining vertical space created by the larger middle container.

The flex-items can also be vertically centered using the  center  value. The very first example of this guide uses the center values for both axes (justify-content and align-items) to create the sweet symmetrical effect on top of the background image.

Align-items: flex-start
Placeholder Picture
FLEX-ITEM-1
Placeholder Picture
FLEX-ITEM-2
Placeholder Picture
FLEX-ITEM-3
Align-items: flex-end
Placeholder Picture
FLEX-ITEM-1
Placeholder Picture
FLEX-ITEM-2
Placeholder Picture
FLEX-ITEM-3

The last property that can be used here is   baseline . This could be useful when the different flex-items would use different fonts or font-sizes. Using baseline as value, the items would be aligned according to the baseline of the font.

Overall the align-items property works in a similar way to the justify-content property, only on the other axis than specified by the flex-direction. This means that if you change the flex-direction, the justify-content and align-items controls switch the axis they were working on. Something to take into account!

align-content

When there is more than a single line — more than a single column or row — of items, this property can be used to distribute the space between the lines. Additional lines are created when there’s not enough space for the flex-items and they are told not to shrink using  wrap .

Let’s create a little playground by reusing the quote section that we looked at earlier. I extended it a bit by adding two more elements and using real customer quotes for (Responsive Foundation Framer) that by nature have varying text lengths.

I also removed the width constraint from the row to give the quotes more room on large monitors. The column (flex-container) now has a minimum height, giving us more vertical room to play with.

The very first thing that comes to mind when looking at that section is how awesome Responsive Foundation Framer easy flexbox makes it to align elements with varying height. No matter the what display width is, the items will line up (and neatly wrap) when space is limited. 

"@CoffeeCup You guys saved us HUNDREDS of dollars with your Responsive Foundation Framer. Thank you! #webdev #coding"
"It's components and symbols which really has me excited. "
" Again...wow! #Foundation Framer by @CoffeeCup Software. "
" When comparing it to other WYSIWYG responsive designers like Adobe Muse, Xara and others, the primary benefit (other than ease of use, which is subjective, and of course, cost) is that Foundation Framer outputs clean, readable code."

Any questions thus far? Please hit me up on twitter so we can discuss!

In the example above I am using  flex-end  for the align-items control and  center  for center for align-content. This vertically centers the boxes and aligns the bottom borders in Firefox, Safari and Internet Explorer. Chrome used to do this differently by positioning the elements at the bottom (flex-end) of the flex-container, but this seems to have been fixed in newer versions.

Placeholder Picture

The flex value for the example above.

Properties for (individual) flexbox-items

Up to now we have been looking at the layout variations using property controls and values for the (parent) flex-container. An additional number of display possibilities can be created by defining flexbox rules for the (direct) children in the flex-container.

Reordering child-elements

Initially the elements inside a flex-container are displayed in the order they were added. We already saw that this order can be reversed using the flex-direction property on the flex-container.

All we need for that is to assign order values. Using a value of   1  for the last flex-item and  2   for the middle item, will make them swap positions. All integer values are allowed here. Giving the third item a value of   -1  would make it the first placed element.

The order property available for the flex-items gives additional control over the order in which the elements are presented. Reusing the example with the horizontally centered items, we can switch the position of the third and second flex-item.

Since these items share the same clase, values for flexbox items should be assigned to a different selector. A good rule of thumb is to use an additional class if the value is shared between a subset of the flex-items, and to add an ID if the value is specific to only one flex element. Order numbers are generally unique so I assigned them to separate IDs.

Placeholder Picture

The Order value for item-2 (on de ID, hence the yellow indicator).

Reorder items 2 and 3
Placeholder Picture
FLEX-ITEM-1
Placeholder Picture
FLEX-ITEM-2
Placeholder Picture
FLEX-ITEM-3

Give that element <picture> link a follow if you have a second. It’s offering something we all should be using more!

Changing the order of items can be useful when layout changes are needed for different screens. Let’s consider a practical use case.

Real life content reordering

Product or service presentations are frequently laid out using a combination of text and images next to each other on wider screens. Then, the order of the image and text for the product or feature on the next line is reversed. However, with less horizontal space available on small screens, many prefer to stack the elements there.

We are using a similar format on many of our pages for describing features of our software products.

On our Responsive Site Designer page, for example, we talk about increasing website performance using the <picture> element. Following that we discuss adjusting layouts for an optimal viewing experience on any screen. It would be weird if these two text sections would follow — would be stacked on top of — each other on mobile devices. The separation of the two features would not be visually clear to the reader.

To battle that we are "pushing and pulling" the columns. This can very well be done both manually and (using the span dropdowns) in Foundation Framer, but requires some conceptual layout thinking. Flexbox makes this way smoother and easier.

The design below uses a similar layout as just discussed.

flex-item-1
FLEX-ITEM-1

NET WT. 6.2 OZ

$ 24.00

Simply work into a lather with warm water and massage onto wet face, rinse clean. For traditional wet shaving: With a wet shave brush or hands, work into a rich lather with warm water and apply to damp beard. Proceed to shave with preferred razor for a close, smooth, clean and moisturizing shave. The rich lathering quality of our Glycerin along with the infused Vitamin E, Safflower, Palm and Coconut oils will protect your skin and provide optimal blade glide – without any residue left behind.

Add to cart
flex-item-2
FLEX-ITEM-2

NET WT. 6.2 OZ

$ 29.00

Simply work into a lather with warm water and massage onto wet face, rinse clean. For traditional wet shaving: With a wet shave brush or hands, work into a rich lather with warm water and apply to damp beard. Proceed to shave with preferred razor for a close, smooth, clean and moisturizing shave. The rich lathering quality of our Glycerin along with the infused Vitamin E, Safflower, Palm and Coconut oils will protect your skin and provide optimal blade glide – without any residue left behind.

Add to cart

Bye bye push & pull. Hello order!

In a mobile-first workflow the elements are often initially stacked — they are visually and physically ordered from top to bottom. On wider screens items can start to 'flow' next to each other. Keeping their natural order they flow from left to right — higher items are positioned on the left of lower items until no space is remaining. Then the next lower item starts on the left on a new line.

View the natural order in the Inspector

In Foundation Framer the natural order is can be easily been seen by selecting an element and going to the Inspector pane. This is the last tab on the top right. Alternatively you can right-click the element and use the 'Got to' function.

In our example this would place the product description section for both items on the left, and the pictures on the right. A rather boring layout that is not very appealing from an aesthetic perspective. The lack of visual separation and could also cause the visitor to skip the second section and even be potentially confusing. 

With flexbox, changing the layout order is effortless. I simply added a class to the picture element. Then, on the flexbox section on the Design pane I gave the Order property of the picture a value of  1   on the 768px breakpoint.

Screen readers and element order

Please note that screen readers will continue to follow the natural order of the elements. It is unlikely, but just as an example, if we would want the screen readers to follow the image+text → text+image order, we should add the elements in that order. Then we could change the visual order of the image and text container if desired.

Influencing element size with flexbox

The ability to calculate and distribute space is one the greatest strengths of flexbox. The flex grow, shrink and basis properties can be used to influence how the available space in the parent (flex) container is allocated between the flex-items.

The flex-basis CSS property specifies the initial size of a flex item. The default value is  auto   which instructs the browser to use the currently calculated width or height. In our examples where each of the flex-items (the white containers) used the same width (100%), the space gets distributed equally.

A specific initial flex-size can be defined as well. The value can be set in pixels, ems, a percenlabele and so on. The unit switcher allows you to choose the best metric for the specific design case. We will look into a really cool example further down below!

First, a simpler example to get the hang of this. Below, each of the white containers uses an ID with individual values for the flex-basis. The middle container is instructed to use  40%  of the space, whereas the other two containers each get  15% . This means that 30% of the space is left empty….but only as long as flex-grow is set to  0 !

Flex-basis: 15%, 40%, 15%
Placeholder Picture
FLEX-ITEM-1
Placeholder Picture
FLEX-ITEM-2
Placeholder Picture
FLEX-ITEM-3

The flex-grow property determines what will happen with any remaining empty space. When changing the flex-grow value to  1   for flex-item-1 it will take up all the space that was left. This makes the element 45% (15% + 30%) of the column width. (Minus any allocated margin or padding.)

If the flex-grow for item-3 is set to  1   as well, the leftover space is equally distributed between both items. That also means that item-2 remains the same size. This is illustrated in the example below.

The flex-grow is not relative to other items. An element with flex-grow of 4 will not always be twice the size of an item with a flex-grow of 2. Increasing the flex-grow for an item just means that the amount of remaining space it receives will be increased.

Increasing, for example, the value to   2  for the first item, would give it twice as much of the leftover space as the last item. And so on.

Placeholder Picture

The Flex values for items 1 and 3

The flex-shrink property works in a similar way. It determines which of the items needs to lose most of its size to compensate for any missing space.

This is the case when collectively the flex items are instructed to take up more space than the parent element.

Flex-basis: 15%, 40%, 15% Grow: 1, 0, 1
Placeholder Picture
FLEX-ITEM-1
Placeholder Picture
FLEX-ITEM-2
Placeholder Picture
FLEX-ITEM-3
Horizontal alignment, an old nightmare

Keeping action buttons or links horizontally aligned underneath a text section, has always been one of the challenges when designing responsive layouts. Even with similar text lengths, sentences of one section would wrap differently than other sections. This then would push items positioned underneath, such as buttons, down before getting pushed down in other sections.

The example below shows three flex containers. The images are the same size, the headings are the same, as well as the paragraph styles. The only difference is the text length of each paragraph.

It is immediately noticeable that the buttons seem to be dancing all over the place. The very restless effect can cause the reader to lose focus and abandon the page or site.

We already saw that Flexbox can be used to create containers of the exact same height, even if the contents within the cards differ. Next let's see if we can it to keep items horizontally aligned, even if the heights of the content elements differ.

Placeholder Picture
FLEX-ITEM-1

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Add to cart
Placeholder Picture
FLEX-ITEM-2

Quisque eleifend gravida libero, vitae ultricies augue blandit vel. Mauris dictum purus in dictum ultrices. Integer id odio ac erat sagittis mattis non at nunc.

Add to cart
Placeholder Picture
FLEX-ITEM-3

Phasellus consequat, sapien id varius fermentum, justo erat ultricies ante, sed aliquet justo quam eget mi.

Add to cart
Maintaining horizontal alignment

In the next example the action buttons are perfectly aligned with each other. This happens because of two reasons. First, the cards (containers) with less content stretch as much is needed to have the same height as the container with the most content. Secondly, the paragraphs are instructed to take up any remaining available space that is created because of the stretching.

Earlier we learned that instructing an element to take up remaining space can be accomplished with the flex-grow property. With a value of  1  — and an implied value of zero for the other elements — the paragraph is greedy and consumes all left-over space. With a background applied to the paragraph this would have been visible.

If you are reading this guide in Responsive Foundation Framer,  I invite you to apply that background to the paragraph and look at the effect. Another useful exercise would be to remove the   flex-grow   class from the paragraph of the first (or last) item. The flex-growth is tied to this selector and without it, the button will immediately move back up right under the text.

The flex-grow (and its counterpart flex-shrink) property might take a little to get used, but they can be very powerful allies in a document where element and layout dimensions change based upon available display width. As we touched upon earlier, a flex-grow value of 2 for an element means it can take up twice as much of the remaining space as elements with a value of 1. Can you imagine the possibilities?

Placeholder Picture
FLEX-ITEM-1

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Add to cart
Placeholder Picture
FLEX-ITEM-2

Quisque eleifend gravida libero, vitae ultricies augue blandit vel. Mauris dictum purus in dictum ultrices. Integer id odio ac erat sagittis mattis non at nunc.

Add to cart
Placeholder Picture
FLEX-ITEM-3

Phasellus consequat, sapien id varius fermentum, justo erat ultricies ante, sed aliquet justo quam eget mi.

Add to cart
align-self

The alignment specified by align-items on a parent level can be overridden for individual flex items. In the example below the first item is displayed according to the align-items: flex-start  rule defined by the parent.

The second items get an align-self: center   rule specified on the ID selector. The third item is told to position at the bottom of the container using flex-end.

The vertical space that is needed for this design example is created by giving the parent container a minimum height.

Align individual items
Placeholder Picture
FLEX-ITEM-1
Placeholder Picture
FLEX-ITEM-2
Placeholder Picture
FLEX-ITEM-3

Please note that the above items will display horizontally aligned in Internet Explorer 11 due to the height related flexbug described at the start of this guide.

using flex-o-magic

The example below uses flex containers with different classes than in the previous examples. However, styles have been added to make the (container) card look similar to the other examples and demos. That's all cool and fun, but not the magical part...

The 'flex-o-magic' is that the cards automatically flow and reposition based upon the available display space...even without receiving specific repositioning instructions at breakpoints!

This magic is performed by a clever combination of flex settings. Before the smallest (custom) breakpoint, we the cards are instructed to display as a flex row by their parent. They are also instructed to wrap to the next line in case there is not enough space. That means that as soon as there's enough space, the cards will reposition and flow next to each other. Now this is the interesting part, when exactly is the space considered to be enough?

The flex-items will consider the space to be enough as soon as they can reach their target width. In this case this target is determined by the specified flex-basis value of  280px . As soon as the width (of the parent) gets to 620px (280px for each card plus 60px margin), the first two cards will be positioned next to each other. Similarly, at 930px all three cards will be flowing next to each other.

A few more things that are worth mentioning here. First of all, the 'target width' does not have to come from the flex-basis property, it can also me determined by other properties such as width.

Secondly, I updated some of the values at another custom, 1400px breakpoint. Instead of allowing the cards to grow indefinitely, I changed the flex-grow value to  0  and gave them a new flex-basis value of  380px . Not absolutely needed, but a nice demonstration and design tweak I felt more comfortable with.

Please note that the flex-grow value of 1 was needed when the cards were wrapping at smaller widths. This setting would make them expand the full width, keeping the design balanced.

Finally, one more 'trick' was used to always horizontally align the paragraphs. You see, the header text was sometimes wrapping for one card, but not the other(s). This would push that paragraph down, while the other stayed in placed. I accounted for that by adding a min-height to the heading that is slightly higher than the height of a wrapped heading. 

Automagical alignment and positioning

The History of CoffeeCup Software

Did you know we brewed the worlds very first HTML Editor? From a coffee shop!?

Learn more

The road to a Design System

The only way to complete a mission like that? Hard work and step-by-step.

Learn more

It’s about creating experiences. Not code!

Visual CSS, easy to manage custom breakpoints, width slider, prototyping and designing in the flexible production environment (browser and more...

Designers rejoice!

Learn more

Wrapping it up

The web is not a fixed-size magazine, but a fluid medium where content needs to flow and flex to provide stellar user experiences, on any of screen size or device. And as we have seen, flexbox is a great tool to do just that.

This guide covers all flexbox aspects from a real world design perspective. It might have taken a little longer to go through, but after this you will be ready to start flexing away and incorporate these approaches in your own work.

If there are specific flexbox design cases you would like to see or if you have any feedback in any type or form, just drop me a tweet or let us know on the official @CoffeeCup Twitter or Facebook accounts.

If you like what you read here you also might want to check out our guide for designing responsive table with flexbox.

I hope you enjoyed it!

Bob Visser
Real Time Web Analytics