CSS Box Model

As per the CSS Box Model, every HTML element is surrounded by a box. And each box has the following four parts:

  • Main Content: The actual content part of the element. The said box is actually wrapped around the content of the element. The content can be anything like an image or text etc.
  • Padding: A transparent space immediately around the content.
  • Border: The outer border for the padding.
  • Margin: A transparent space outside the border.

The main purpose of the box model is to have a neat, well-defined space among the various elements. A simple example goes as follows:

Box Model Height and Width

As per the box model, the height and width properties of CSS can only control the height and width of the content area. Therefore, the actual rendered height and width of the elements might be more than the value set for the two properties due to the padding, margin and border. Here’s a simple formula to calculate the total width and height of the element:

Total Width = Width Set + Left Margin + Right Margin + Left Border + Right Border + Left Padding + Right Padding
Total Height = Height Set + Top Margin + Bottom Margin + Top Border + Bottom Border + Top Padding + Top Padding

Therefore, in the above example

Total Width = 300px + 30px + 30px (left and right margins) + 25px +25px (padding) + 20px +20px (border) = 450px
Total Height = 300px + 30px + 30px (left and right margins) + 25px +25px (padding) + 20px +20px (border) = 450px

Remember, we are using the shorthand properties for margin and padding and therefore, the same single value given will be taken for all sides.