Tech Interview RoomStudy guides

HTML & CSS

Explain the CSS box model and box-sizing.

Beginner · 2 min read · Lesson 2 of 7 in HTML & CSS

Every element is a rectangular box made of four layers, from inside out:

  1. Content: the text or image, sized by width and height.
  2. Padding: space inside the border; takes the element's background.
  3. Border.
  4. Margin: space outside the border; always transparent.

box-sizing

  • content-box (the default): width sets only the content. A width: 200px box with padding: 20px and border: 1px is actually 242px wide.
  • border-box: width includes 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

css
*, *::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.