CSS Box Model


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

While creating the layout of a web page, the browser's rendering engine calculates the size of each box and the placement of each box on the page according to the standard CSS box model.

The properties and sizes of the box model can be changed using CSS.

Every HTML element can be compared with a box. Treating HTML elements as boxes we can visualize an element size using these 4 properties:

CSS box model
CSS box model

The above image shows the box model of an element. Content, padding, border, and margin of the element combined form the height and weight of the element.


Content

Content is the main part of the box model. It is the actual text or image that is displayed on the page.

It is surrounded by padding of the element (if any).


Padding

Padding is the internal space of the box model around the content. It takes its own space.

It is surrounded by the border of the element.


Border

The border is the line that surrounds the padding and content of the element.

It is surrounded by the margin of the element.


Margin

Margin is the external space of the box model. It is the space between the border of the element and the border of the adjacent element.

It is not part of the element.


Effective Height and width of the element

The effective height and width of an element is the total height and width of the element including content, padding, border, and margin.

From the above figure you can see that the effective height and width of the content are:

Example

div {
    margin: 15px;
    border: 5px solid gray;
    padding: 20px;
    height: 50px;
    width: 300px;
}
Try it