i

Learn HTML and CSS in 10 Days

Working With Box Model

As said earlier, every element present on the web page is a rectangular box. Each of them is linked with several properties that specify the box's size. The center of the box is characterized by the height and width of the element. Border and Padding define the outward dimension of the element's height and width. And lastly, we have the margins.

Thus each piece of the box model relates to a CSS property: height, width, border, padding, and margins.

Let's look at code:

div {

  border: 6px solid #949599;

  height: 100px;

  margin: 20px;

  padding: 20px;

  width: 400px;}

As per the box model, one can determine the net width of an element by using the formula below:

margin-right + border-right + padding-right + width + padding-left + border-left + margin-left

So let’s use the formula for the above code:

Width (492px) = 20px + 6px + 20px + 400px + 20px + 6px + 20px

Likewise to determine the total height of the box model element you can use the following formula:

margin-top + border-top + padding-top + height + padding-bottom + border-bottom + margin-bottom

So let’s use the formula for the above code:

Height (192px) = 20px + 6px + 20px + 100px + 20px + 6px + 20px

To be very honest, the box model is the most confusing section of HTML & CSS. Like in the above case, we set the width property value as 400 pixels, but after calculating, we found that the actual width of the element is 492 pixels. So it is clear that the box model is additive. To get the real size of a box, you need to take borders, padding, and margins of all the four sides into consideration. 

So far, a great deal of these properties probably won't bode well, and that is okay. So tackle it, let's have a closer viewpoint at all of these properties – height, width, border, padding, and margin.