CSS box model
Блочная модель
The CSS box model describes an element’s content, padding, border, and margin. The `box-sizing` property controls whether a declared width or height includes the padding and border.
Also known as: box-sizing
Think in layers
When a browser lays out a page, it calculates the size and position of boxes. The box model explains what those boxes are made of. Picture a button: its label is the content, the space between the label and the edge is padding, the outline drawn with border is the border, and the space outside that border is margin. An element’s background normally extends through the padding but never paints its margin.
The term isn't limited to block-level elements. An inline link can have padding and a border too, even though a declared width won't resize an ordinary inline text box.
What does width actually measure?
That depends on box-sizing, a property of the box model rather than another name for it:
content-boxmeasures the content area. To get the width from one outer border edge to the other, add the left and right padding and border widths. This is the property's initial value, although browser styles can set a different value for some elements.border-boxmeasures from border edge to border edge. Padding and borders take up part of the declared width, leaving the rest for content. If the padding and borders alone exceed that width, the content width bottoms out at zero and the box can still be wider than declared.
The same distinction applies to height. Neither setting includes margins in the declared size.
Example: a field that needs to fit
.search-field {
width: 100%;
padding: 8px 12px;
border: 1px solid;
box-sizing: border-box;
}
In a simple layout where the containing block is 320px wide, the field is 320px across at its border edges and has 294px of content width: 320 − 2 × 12 − 2 × 1. With content-box, the content alone would be 320px wide, and the border box would grow to 346px. This is why border-box is useful for fields or cards that need to fit a particular width. It won't fix every overflow: horizontal margins still sit outside the box, and min-width can still force the field to be wider.
Debugging and interview questions
When an element looks wider than its CSS suggests, inspect the box model diagram in browser DevTools. Check the computed box-sizing first, then compare the content width with the padding, borders, and margins on each side.
In an interview, you may be asked for an element's “total width.” Say which edges you're measuring: the content width, the border box, or the width including margins. A common follow-up is why two paragraphs with margin-bottom: 16px on the first and margin-top: 24px on the second may be only 24px apart. In normal block layout, adjoining positive vertical margins can collapse to the larger margin rather than add together. That behavior is separate from box-sizing.