Flexible, Grid-Like Layouts in CSS

Update: I’ve made some comments on cssnewbie.com talking about how this technique is useful for magazine-type layouts and is actually more semantic in that case.

Just when you assumed that everything that could be done in CSS has already been done, the geniuses at A List Apart have really come up with a potentially revolutionary technique.

I haven’t yet wrapped my head around it, but Eric Sol has posted a wonderful A List Apart article about achieving flexible, grid-like layouts in CSS.


Example of Faux Absolute Positioning in action. (by Eric Sol, A List Apart)

The basic idea is to use position: relative; left: 100%; margin-left: -##% (non-percent units such as px also work). Eric calls the technique “Faux Absolute Positioning”. The items generally have the same behavior as inline elements and avoid some of the fragility of floats. Eric explains the inspiration for the technique:

Our use case was even more complex: my team was developing a web-based WYSIWYG form generator that allows the user to drag items to arbitrary locations on a canvas. We needed to let our users create beautiful forms that didn’t use overly static layouts and to let them align columns as needed.

For example, let’s assume we want a form that puts the postal code and city fields on the same line because they are semantically connected. To accomplish this, we tried using floated positioning inspired by the Holy Grail technique. Using this method, we needed to adjust the width, borders, margins, and/or padding of the postal code field to pin the city field to a fixed horizontal position. That was a problem because if the width of the postal code field needed adjusting, or if we wanted to adjust the amount of whitespace between fields, the city field would need to move as well. The more elements on a page–the more cells in your grid–the more tedious this kind of adjustment becomes. Additionally, the positioning is sensitive to the slightest change in a number of parameters, which makes it nigh impossible to control in case of dynamic form items.

Next, we tried using absolute positioning. This gave us much more control over the positioning of the items and is robust. But absolutely positioned elements have no height, and that caused the containing element (the canvas) to collapse. This made it hard to position content without making everything absolutely positioned–which is impossible to achieve with dynamic content.