JSTAcademy
0 XP
Dashboard
Crash Courses
The CSS Box Model
11 min
Basic+150 XP
Crash Courses · Basic

The CSS Box Model

Understand how every element is sized and spaced — margin, border, padding, and content.
11 min read+150 XP on completionCert: HTML & CSS Crash Course
Tap any word in the text below to start reading from there.

The CSS Box Model

Every element is a rectangular box: content + padding + border + margin.

box-sizing: border-box

*, *::before, *::after {
  box-sizing: border-box;
}

Without it: width: 300px means content is 300px, then padding and border ADD MORE.

With it: width: 300px means the entire box is 300px.

Tailwind applies border-box automatically. Always add this to vanilla CSS.

Margin and Padding

margin: 16px;                    /* all sides */
margin: 16px 24px;               /* top/bottom, left/right */
margin: 8px 16px 12px 16px;      /* top right bottom left */
margin-top: 8px;
padding: 24px;

Margin Collapse

.first  { margin-bottom: 24px; }
.second { margin-top: 16px; }
/* gap = 24px, NOT 40px */

Vertical margins between block elements collapse to the larger value. Flex/grid children do NOT collapse.

Width and Height

width: 300px;       /* fixed */
width: 50%;         /* relative to parent */
width: 100vw;       /* viewport width */
min-width: 200px;
max-width: 1200px;

Overflow

overflow: hidden;   /* clips content */
overflow: auto;     /* scrollbar only when needed */
overflow-x: auto;   /* horizontal scroll only */
0%