CSS Tutorial

Box Sizing

Every HTML element has a box model consisting of four components:

  • content
  • padding
  • border
  • margin.

Box-sizing: content-box (Default):

  • The width and height of an element include only the content area.
  • Padding and border are added outside the element's dimensions.

Box-sizing: border-box:

  • The width and height of an element include the content, padding, and border.
  • Padding and border are within the element's dimensions.

Practical Steps:

  • Add the box-sizing property to the style declaration of any element.
  • Set it to either content-box or border-box based on your desired behavior.

CSS Example:

/* content-box */
.element {
  width: 100px;
  padding: 10px;
  border: 1px solid black;
  box-sizing: content-box;
}

/* border-box */
.element2 {
  width: 100px;
  padding: 10px;
  border: 1px solid black;
  box-sizing: border-box;
}

In this example, element will have a total width of 122px (100px content + 10px padding + 10px border on both sides), while element2 will have a total width of 100px (padding and border are included within the width).

Benefits of Using 'border-box':

  • Simplifies layout calculations.
  • Ensures consistent spacing between elements.
  • Facilitates responsive design by allowing elements to shrink responsively without affecting content.