CSS box model

The CSS box model is essentially a box that wraps around HTML elements, and it consists of: margins, borders, padding, and the actual content.

The box model allows us to add a border around elements, and to define space between elements.

The image below illustrates the box model:
box-model

Explanation of the different parts:

  • Content – The content of the box, where text and images appear
  • Padding – Clears an area around the content. The padding is transparent
  • Border – A border that goes around the padding and content
  • Margin – Clears an area outside the border. The margin is transparent

Examples

Example using two divs inside a container div with content, padding, border and margin set.

Notice the margin of the first box – it is affecting the container div and pushing all content down to make room for itself.

Also notice the margin collapse between the two boxes with a blue background color.

Notice how [background-color: blue;] is what would typically be covered when switching to [background: url (“/images/somepicture.jpg”);].  A background image covers content, padding and border.  An inline image only covers content.

Example using block-inline for the container div and a spacer div to prevent margin collapse.

CSS box model was last modified: May 26th, 2015 by tabcom