Sobes.tech
Junior

Τι είναι το μοντέλο κουτιού στο CSS;

sobes.tech AI

Απάντηση από AI

The CSS box model describes how elements are displayed on the page as rectangular blocks. It consists of four zones or layers that overlap, starting from the content:

  1. Content: The area where the actual content of the element (text, images, etc.) is located. Its size is determined by the width and height properties.

  2. Padding: The transparent area between the content and the border of the element. It is set with padding-top, padding-right, padding-bottom, padding-left, or the shorthand padding.

  3. Border: The line surrounding the padding and content. Its style, thickness, and color are set with border-width, border-style, border-color, or shorthand like border.

  4. Margin: The transparent area around the border of the element, separating it from other elements. It is set with margin-top, margin-right, margin-bottom, margin-left, or the shorthand margin. Margins of adjacent blocks can collapse.

The default behavior, described by box-sizing: content-box (default), specifies that width and height properties only relate to the content. Padding and border are added to this size, increasing the total size of the element.

Using box-sizing: border-box, the width and height properties include content, padding, and border. Margin is always added to the total size of the element, regardless of box-sizing.

Example:

div {
  width: 100px; /* Content width (for content-box) or total element width (for border-box) */
  height: 50px; /* Content height (for content-box) or total element height (for border-box) */
  padding: 10px; /* Inner padding */
  border: 2px solid black; /* Border */
  margin: 15px; /* External margin */
}

Depending on the value of box-sizing, the actual sizes of the element will differ.

  • box-sizing: content-box: Actual width = 100px (content) + 10px (padding-left) + 10px (padding-right) + 2px (border-left) + 2px (border-right) = 124px. Actual height = 50px (content) + 10px (padding-top) + 10px (padding-bottom) + 2px (border-top) + 2px (border-bottom) = 74px.
  • box-sizing: border-box: Actual width = 100px (content + padding + border). Actual height = 50px (content + padding + border).

The external margin margin: 15px is added around this total size.