Box Model

06 Aug 2023 . css .

CSS Box Model

Describe the rectangular boxes that are generated for elements in the document tree.

Responsible for calculating:

  • How much space a block element takes up.
  • Whether or not borders and/or margins overlap, or collapse.
  • A box’s dimensions(尺寸).

The box has the following rules:

  • The dimensions of a block element are calculated by width, height, padding, border and margin.
  • If no height is specified, a block element will be as high as the content it contains, plus padding.
  • If no width is specified, a non-floated block element will expand to fit the width of its parent minus padding.
  • The height of an element is calculated by the content’s height.
  • The width of an element is calculated by the content’s width.
  • By default, padding and border are not part of the width and height of an element.

box-sizing: border-box

By default, elements have box-sizing: content-box applied, and only the content size is being accounted for.

box-sizing: border-box changes how the width and height of elements are being calculated, border and padding are also being included in the calculation.

  • The height of an element is now calculated by the content’s height + vertical padding + vertical border width.
  • The width of an element is now calculated by the content’s width + horizontal padding + horizontal border width.