CSS Box Model

HTML elements consists of inline and block elements. All of them are box models even for inline elements such as <em>, <span>, or <strong>. Each box has it’s own (default) border, margin, and padding size.

Put the following CSS code to your web pages to see (the box) by yourself temporarily:

* { border: 1px solid red !important; }

With the above CSS, all elements will have a 1px solid red border around it’s content area.

Margin is a space between box border and it’s outside elements, padding is a space between box’s border and it’s containing contents. Below is an image which describe padding, margin, border of a box model.


The box element is the area which has orange-ish color. The box has solid border. Inside the box there is a content “The Box Content”, space between border and “The Box Content” is called padding. The space between border and outside elements of the box is called margin.

Box border size, padding, and margin in HTML is modifiable via CSS. For example, to have a box model (e.g. a paragraph element) which has 10px margin, 20px padding, and 5px in size black solid border on all of it’s sides can be defined by a CSS below:

p {
    border:5px solid black;

Elements Size

The size of elements are calculated as follow:

Total width = element’s width + padding-left + padding-right + margin-left + margin-right + border-left-size + border-right-size

Total height = element’s height + padding-top + padding-bottom + margin-top + margin-bottom + border-top-size + border-bottom-size

if those element values are undeclared, then it falls back to the browser’s default value (usually has 0px in size).

Margin Collapse

When two or more side-by-side elements which has the same or different margin size, a margin-collapse occur between those elements. This event is explained by a picture below:


There are two boxes A and B which are positioned top and bottom (it is also happened on side-by-side) of each other. The top box (Box A) has margin-bottom of 30px, and the bottom box (Box B) has margin-top of 20px. Then margin collapse between those two boxes occured. The margin space between them become collapsed and the effective margin space between them become the largest between those two, in this example. The effective margin between box A and box B are become 30px (this is the margin-bottom value of Box A) as margin-bottom of Box A is larger than margin-top value of Box B.