CSS Box Model

All HTML block-level elements have five spacing properties: height, width, margin, border and padding. Together, they form the box that the element takes up.

Each box has a content area (e.g., text, image, etc.) and optional surrounding padding, border, and margin areas; the size of each area is specified by properties defined below. The following diagram shows how these areas relate and the terminology used to refer to pieces of margin, border, and padding:

Image illustrating the relationship between content, padding, borders, and margins.

The margin, border, and padding can be broken down into top, right, bottom, and left segments (e.g., in the diagram, "LM" for left margin, "RP" for right padding, "TB" for top border, etc.).

The perimeter of each of the four areas (content, padding, border, and margin) is called an "edge", so each box has four edges:

  • content edge
  • padding edge
  • border edge
  • margin edge

Default margins, borders and padding are all 0, so when you wrap a div around some text, there is no space between its edges and the text. Default widths for all block-level elements are 100%. The height of an element relies entirely on its contents.

The block-level elements (e.g. h1) add line breaks around themselves , while inline elements (like em) can be introduced into a page without causing too much disruption.

CSS has a powerful property, display, which allows you to change the way an element displays. You can make an inline element display like a block-level element or vice-versa. So, we could have a line like

p {display: inline; }

With this, all of your paragraphs would display as one long line, as they are no longer block-level elements.

All block-level elements also have the properties width and height. The margins, borders and padding you add to each element are then added on to these dimensions. Say you define a paragraph,

p {width: 600px; padding: 5px; }

This paragraph will take up 610 horizontal pixels on the page, as a padding of 5 pixels is added on to each side

CSS and Spacing