Tuesday, November 13, 2012

CSS Box Model

Every element is considered as box consisting of margin, border, padding properties. The box model is used for adjusting the margin, border, padding and content of the element. The box model is shown in the following image:

Explanation of the above image:
Element Content: The inner most box, where text and image are placed.

 Padding: It is a space between the element content and border of the element.

Border : The border goes around the element content and padding.

Margin: It is the area around border of the element.

The above properties have four edges “top, right, bottom, left”. Whenever we set height and width of the element we set it only for element content of the element. To calculate the total area of the element we need calculate the area of element with margin, padding and border.

Following is simple example for the box model:

Height: 10px;
Padding: 10px;
Margin: 10px;
Border: 10px;

Total height of the element:10 height + 20(padding) +20(margin)+20(bordefr)= 70px.

Now the question is the defined value of the padding is 10 but we are calculating with 20px, it is because when the padding implemented it is on all the sides for left, right, bottom, top so each side will have 10px of padding. So the height will contain the total padding of the top+ bottom. Same will be applied to the border and margin properties.

Total width of the element:10 width + 20(padding) +20(margin)+20(bordefr)= 70px.