What is box model in CSS?

Updated on Jun 20, 2021/css-conceptscss

In CSS, the box model describes the rectangular boxes that are generated for elements in document tree and laid out according to the visual formatting model, standardized in CSS Box Sizing Module Level 3.

box

Each box has a content area (text, image, etc.) and optional surrounding padding, border, and margin areas. The diagram shows how these areas relate and the terminology:

  • Content: The content of the box, where text and images appear.
  • Padding: Clears a transparent area around the content.
  • Border: A border that goes around the padding and content.
  • Margin: Clears a transparent area outside the border.

The total width and height of an element is calculated based on box-sizing property, specifying whether or not an element’s borders and padding should be included, margins always excluded.

  • content-box (default): The width and height properties include the content, but does not include the padding, border, or margin. When you set the width and height properties, you just set the width and height of the content area.
  • border-box: The width and height properties include the content, padding, and border, but do not include the margin. When you set the width and height properties, you set the width and height of the border area.

It is often useful to set box-sizing to border-box to layout elements. This makes dealing with the sizes of elements much easier, and generally eliminates a number of pitfalls you can stumble on while laying out your content.

The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing.