200928July

CSS3 Flexible Box Layout Module

This article is intended for experienced web designers.

the need for another layout model

I am excited by the new Flexible Box Layout Module draft from W3C. There are many types of web layout designs that require content of a set width along side content that should simply fill some variable amount of leftover space. Such an example is a left navigation column with a right content column. There currently is no good mechanism for doing this; designers hack around this by using things like negative margins and huge padding figures.

This draft attempts to meet that need by allowing the designer to specify that a block or group of blocks should take up whatever space is left over. The draft ads a new display property to the existing inline, block, inline-block, table-cell et al. It is called box. Children of the box element may be oriented horizontally or vertically and may themselves be boxes with either horizontal or vertical orientations.

box-flex

The neat part is the box-flex property assigned to each child. By default, the children are assigned a box-flex of 0, which is inflexible. It can be set to any nonnegative floating point number. This number is used to describe how much it flexes, relative to other flexible elements in the box. For instance, if I have a box with three children with box-flexes of 0, 1, and 2:
<div style="display: box; width: 500px;"> <div style="box-flex: 0; height: 300px; width: 100px;"></div> <div style="box-flex: 1; height: 300px; width: 100px;"></div> <div style="box-flex: 2; height: 300px; width: 100px;"></div> </div>
The containing box is wider than the children elements, so the size of the children that are flexible (those with a box-flex greater than 0) will be adjusted to fill the containing box. In this case, the child with the box-flex of 2 will gain twice as much width as the child with box-flex of 1. If both had box-flex of 1, they would each gain the same amount of width. Additionally, if the containing element was smaller than the combined width of the children, the flexible elements would shrink. The properties min-width and max-width may be used to limit a child element from shrinking or growing past a fixed width.

a welcome change

A primary reason people are still tempted to use table based layouts is because there is an easy way to make a cell take up the rest of the unused space. The box-flex property meets and exceeds that requirement. This is a much needed addition to the CSS specification.

Tagged: and