CSS - Working with the BoxModel 🤖

January 10, 2021

How the Box Model Works

Every element is a rectangular box, and there are several properties that determine the size of that box. The core of the box is defined by the width and height of an element, which may be determined by the display property, by the contents of the element, or by specified width and height properties. padding and then border expand the dimensions of the box outward from the element’s width and height. Lastly, any margin we have specified will follow the border.

Each part of the box model corresponds to a CSS property: width, height, padding, border, and margin.

Let’s look these properties inside some code:

div {
  border: 6px solid #949599;
  height: 100px;
  margin: 20px;
  padding: 20px;
  width: 400px;
}

According to the box model, the total width of an element can be calculated using the following formula:

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

In comparison, according to the box model, the total height of an element can be calculated using the following formula:

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

Up next