CSS Box Model Tutorial

In CSS, the term "box model" is a concept that refers to block-level HTML elements, the attributes of the element and how they relate to each other. The box model is made up of the HTML element, padding, border and the margin.

The box model concept is most useful when it is used for positioning purposes when designing css-based layouts and web design.

The box model can be applied to any block level HTML element. There are 2 types of HTML elements: block-level and inline elements.

Block-level HTML elements are elements that create a boxed space which can contain text, data or other elements and generally start new lines of text.

Some examples of block-level elements are paragraphs, headings, tables, etc.

Inline HTML elements generally do not begin new lines of text and generally contain only text, data or other inline elements. Inline elements inherit attributes directly from block-level elements, for example a background color.

An example of an inline element is: <span></span>

The box type of an HTML element can be set using the display property. If you set the display property of an inline element to block, the element will be treated as a block element

The CSS rule below shows you how to use the display property to set an inline element as a block element.

/* the li element within a list is an inline element unless set as a block level element */ ul li { display:block; }

The image below is a visual representation of the box model.

css box model image

An explanation of the box model and its' different parts are listed below.

  • Content - the content area of the box is where text, data and images and other inline elements appear.
  • Padding - the padding is the area between the content area of the box and the border surrounding the content area. The padding inherits the background color of the content area.
  • Border - a border that lies outside the padding area. The border inherits the background color of the content area, or you can set the background color of the background yourself.
  • Margin - the margin clears an area around the border. The margin does not have a background color and is transparent.

Width and Height of HTML Elements

The full size of the box area of a block level HTML element includes the width and height of the content area, padding, border and margin.

The width of an element includes not only the width of the content area, but also the width of the left and right padding area, the width of the left and right border area and width of the left and right margin area. The same applies to the height of an element.

Internet Explorer and Block-Level Elements

IE (Internet Explorer) includes padding and border in the width of the content area, unless a DOCTYPE is declared. Simply make sure that a DOCTYPE is included in the HTML document to fix this issue.