CSS stacking with display:table

With responsive design, one of the things that we often want to do is to change the stack order of certain elements, moving the aside on the left below the main text which we want to bring to the top. CSS3‘s Flexbox will do this for us, but there is a quicker, if dirtier, way which we can use now.

We can easily change the ordering of these boxes in a media query, say at 48em (768px) by taking advantage of display:table. For demo purposes, we’ll put box three at the top, followed by box four, two and then one.

First of all we need to set the containing element, .boxes as display:table.

Then we set the element we want at the top, Box Three, as display:table-caption.

To push an element to the bottom, in this case Box One, we set display:table-footer-group.

And finally to push an element to the top, but not the very top we set Box Four to display:table-header-group.

Now I know that purists will probably be appalled by this, I know that I am a bit, but I will admit to having used it in production code simply because it works and it’s a lot less hassle than the various incarnations of Flexbox at the moment. It also works cross browser down to and including Internet Explorer 8.

This “solution”, if I can call it that, also has its limitations as you don’t have the fine tuning of deciding the exact stack order of many elements which Flexbox will give you, but it works well for a small number of elements as the demo shows.

As always, thoughts and comments are welcome.

Update: 11th June 2013

I have updated the demo to show how even Internet Explorer 8 supports these properties for display and orders them correctly. I have used respond.js to help IE8 recognise the required media query.