Explain the CSS box model and box-sizing.
Every element is a rectangular box made of four layers, from inside out:
- Content: the text or image, sized by
widthandheight. - Padding: space inside the border; takes the element's background.
- Border.
- Margin: space outside the border; always transparent.
box-sizing
content-box(the default):widthsets only the content. Awidth: 200pxbox withpadding: 20pxandborder: 1pxis actually 242px wide.border-box:widthincludes padding and border, so the box stays 200px and the content shrinks. Almost every project sets this globally because it makes layouts predictable.
Margin collapsing
Vertical margins between block elements in normal flow collapse: the larger margin wins instead of adding up. It does not happen in flex or grid containers, or with padding or borders between the margins.
Display types
block takes the full width and starts on a new line; inline flows with text and ignores width, height and vertical margins; inline-block flows with text but respects sizes.
Example
*, *::before, *::after {
box-sizing: border-box; /* the common reset */
}
.card {
width: 300px; /* total width stays 300px */
padding: 16px;
border: 1px solid #ddd;
margin-block: 24px; /* logical property: top and bottom */
}Two stacked .card elements end up 24px apart, not 48px, because their vertical margins collapse.
Follow-up questions interviewers ask
Try answering each one before you open it.
What are logical properties?
margin-inline, padding-block, inset-inline-start and friends describe sides relative to the writing direction instead of left and right. Layouts then flip correctly for right-to-left languages such as Arabic or Urdu without extra CSS.