HTML5 and CSS3 Advent 2011

Flexing your flex-box muscle

A long standing problem in CSS is that there is no way to do proper (page)layout. Sure we can hack around with float, display: table (and friends) and position but all of these were never really meant to be used for layout. But the future is bright as there are quite some exciting new layout mechanisms in the W3C specs (grids, regions, exclusions, etc.). Today we're going to focus on one that is somewhat useable: the Flexible Box Model (flex-box).


Warning: This example acts strange in Google Chrome.

Box x

How does it work?

Flex-box allows you to align boxes next to (or below) each other and "pack" them into the containing element. First you have to set up your container by setting display: box. You can also specify the manner of the box placement within that container here by using box-pack for the vertical placement and box-align for the horizontal placement.

For each of the containers you have to decide what amount of flexibility you want to give them. This is done by means of the box-flex property and defines proportions between different elements. This means that two elements with box-flex: 3 should have an equal size and elements with box-flex: 2 are smaller.

The best thing in flex-box is that you can actually place your boxes in a different order than the source with box-ordinal-group. That's quite a big deal as this used to be very difficult to achieve.

A word of warning

A word of warning: the flex-box spec changed considerably in 2011. At the time of writing, current browsers only support the old spec, so that is what we've described and used in these examples.

Another thing is that the support in different browsers is flaky at best; each one of them has weird quirks. It has been said that those bugs won't be fixed as browser vendors will implement the new spec.

Show us the source!

Feel free to look around the different source files we used for this example.

Check out our all new HTML & CSS Advent 2012