Lessons in this course (11)

5. The box model, units and positioning

Basic★ Must knowLesson 5 of 11

Every element is a box: content → padding → border → margin.

css
*, *::before, *::after { box-sizing: border-box; }   /* width includes padding + border — the modern default */
.card { width: 300px; padding: 16px; border: 1px solid #ddd; margin: 12px; }
/* content-box: rendered width = 300 + 32 + 2 = 334px;  border-box: rendered width = 300px */

Margin collapsing: vertical margins of adjacent blocks combine into the larger one (not in flex/grid containers).

UnitRelative toUse
pxFixedBorders, small details
remRoot font sizeFont sizes, spacing (respects user zoom settings)
emParent/element font sizePadding that scales with its text
%ParentFluid widths
vw / vh / dvhViewport (dynamic viewport for mobile bars)Full-screen sections
frFree space in GridGrid columns
chWidth of "0"Readable line length (max-width: 70ch)

Position:

ValueBehaviour
staticNormal flow (default)
relativeOffset from its normal place; becomes containing block for absolute children
absoluteRemoved from flow; positioned to nearest positioned ancestor
fixedRelative to the viewport (stays when scrolling)
stickyNormal until a scroll threshold, then sticks (top: 0)

z-index works only on positioned (or flex/grid) elements and within its stacking context.