Boxes and positioning

Margin and padding

Create internal and external spacing, use logical properties, and recognize when vertical block margins collapse.

8 minute lesson

~~~

Padding creates space inside a border. Margin separates boxes.

.card {
  padding: 1rem 1.5rem;
  margin-block: 2rem;
}

Logical properties such as margin-block, margin-inline, padding-block, and padding-inline follow the writing direction instead of assuming top, right, bottom, and left.

Block-axis margins in normal flow can collapse. Adjacent sibling margins may combine into one, usually the larger positive value. A first or last child’s margin can also collapse through a parent when no border, padding, inline content, height, or new formatting context separates them. Flex and Grid item margins do not collapse.

Do not “fix” an unexplained collapse by adding arbitrary padding. Inspect the boxes, decide whether the spacing belongs to the parent or siblings, and create a new formatting context only when that layout boundary is intentional.

Use gap when spacing items inside a Flexbox or Grid layout. It expresses the relationship on the container and avoids first-child and last-child margin exceptions.

Set two paragraphs to margin-block: 2rem and measure the space between them. Then place them in a flex column with gap: 2rem. The first demonstrates collapsing; the second expresses one explicit inter-item gap.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →