Sobes.tech
Junior

What is the box model in CSS?

sobes.tech AI

Answer from AI

In CSS, the box model describes a rectangular area generated for each element and used to calculate its size and position. It consists of four parts:

  • Content box: The area where the content of the element (text, images, etc.) is displayed. Its size is determined by the width and height properties.
  • Padding box: The space between the content boundary and the element's border. Its size is determined by the padding properties. The element's background color and image extend into this area.
  • Border box: The border of the element surrounding the padding box. Its size is determined by the border properties.
  • Margin box: The space around the element's border, separating it from other elements. Its size is determined by the margin properties. This area is always fully transparent.

The size of an element by default is calculated as follows:

width = width + padding-left + padding-right + border-left-width + border-right-width
height = height + padding-top + padding-bottom + border-top-width + border-bottom-width

The box-sizing property allows you to change this model:

  • content-box (default): The width and height refer only to the content box.
  • border-box: The width and height include padding and border.
.element-default {
  width: 100px; /* Content box width = 100px */
  padding: 10px;
  border: 5px solid black;
  /* Actual element width: 100 + 10 + 10 + 5 + 5 = 130px */
}

.element-border-box {
  width: 100px; /* Actual element width = 100px */
  padding: 10px;
  border: 5px solid black;
  box-sizing: border-box;
  /* Content box width: 100 - 10 - 10 - 5 - 5 = 70px */
}