23 August 2008

CSS layout fundamentals, part 2: the visual formatting model

This is the second part in my series of articles on CSS layout fundamentals. Designed to rid the world of table-based layouts forever, you can find the other parts here:

The visual formatting model

Now we’ve declared everything is is a rectangular box with margins, border and padding, we need to determine how to arrange these boxes on the screen. This is the role of the CSS visual formatting model.

Diagram with boxes scattered all over the place
Lots of boxes — how do we arrange them?

You could never say that the W3C keeps the scope of their standards too small. CSS as a whole attempts to address not just screens, projectors and printers — visual media — but also devices for listening to content, Braille rendering, and other ways to access content. The “visual” formatting model is limited to defining how to render content just for visual media like screens, projectors and paper.

In order to define a rendering model that fits well with the existing structure of HTML, CSS splits boxes into several types with different properties.

There are two primary types of boxes described by the visual formatting model:

  • inline box
  • block box.

Although there are other types of boxes, we’ll limit our discussion to these two major types. There’s enough complexity here to have an interesting discussion, and enough flexibility to create many different types of layouts.

The two types of boxes correspond pretty much with the element types in HTML 4. By default, inline boxes are generated by inline elements, and block boxes are generated by block boxes.

However, CSS provides the ability to change the type of box generated by an element. You do this with the display property. For example, the following CSS style will format paragraphs as inline boxes instead of block boxes:

p {
    display: inline;

As we’ll see later, the ability to change the type of box generated by certain content is critical to creating CSS layouts.

Sometimes, for the purposes of CSS formatting, there are situations where a single HTML element generates multiple boxes in the layout. An example is splitting an inline element into multiple lines. It also sometimes happens that CSS boxes are generated for content without a corresponding element. These are called “anonymous boxes” and you can read more about them in the specification if you’re interested.

The next part will cover the properties of inline and block boxes and how these two combine to create the normal flow.