CSS Visual Formatting: Boxes

TOC

Basic Boxes

CSS assumes that every element generates one or more rectangular boxes, called element boxes. Each element box has a content area at its core. The content area is surrounded by optional amounts of padding, borders, and margins. They are considered optional because they can be set to 0 width, effectively removing them from the element box.

margin

padding

border

This is the content area of a block-level element such as a paragraph.

(The content area and its surroundings)

The Containing Block

Every page element is rendered with respect to its containing block, or the "layout context" of the element. The containing block is formed by the content edge of the nearest block-level, table cell, or inline-block ancestor box. For example:

  <body>
    <div>
      <p>This is a paragraph element.</p>
    </div>
  </body>

In this simple markup, the containing block for the p element is the div element, as that is the closest ancestor element that is block-level, table cell, or inline-block (in this case it is a block box.) The div's containing block is the document body. Thus, the layout of the p is dependent on the layout of the div, which is in turn dependent on the layout of the body.

Block Level Elements

CSS requires block-level elements like paragraphs (p), headings (h1, h2, etc.), divs, ordered and unordered lists (ul, ol), to generate "new lines" both before and after their boxes in the normal flow of the document. The exception to this is the difference between Microsoft Internet Explorer and Gecko-based browsers like Mozilla and Firefox; MSIE only adds vertical space between two or more blocks, while Mozilla always adds vertical space. Blocks stack vertically, one after another. An element that is not normally a block-level element can be changed to one by declaring display:block. Conversely, block-level elements can become inline elements by declaring display:inline.

The following diagram shows the implementation of the box model in current Microsoft Internet Explorer, Mozilla and Firefox browsers:

Width and Height

The CSS standards define the width and height attributes as applying to the content area, not the box. In other words, if I set the width and height of a container, like a paragraph, then start adding padding (which is generated between the edges of the container and the border of the paragraph), the paragraph box will grow to include the padding outside the specified container width and height. Margins add additional width outside the box border.

Mozilla box implementation: MSIE box implementation:

<< Text Attributes | Index | Padding, Borders and Margins >>