The Box Model
margin, padding, border, box-sizing
Skills taught: css.box-model, css.margin, css.padding, css.border
The four layers
.card {
/* Content area */
width: 300px;
height: 200px;
/* Padding — space INSIDE the border */
padding: 24px; /* all four sides */
padding: 16px 24px; /* top/bottom left/right */
padding: 8px 16px 24px 32px; /* top right bottom left */
/* Border */
border: 2px solid #4fd1c5;
border-radius: 8px;
/* Margin — space OUTSIDE the border */
margin: 16px;
margin: 0 auto; /* centre horizontally */
}
Tip: Use browser DevTools (F12 → Elements → Computed) to see the box model diagram for any element. It shows content, padding, border, and margin as coloured rings.
box-sizing: border-box
By default, width sets only the content area. Padding and border are added on top. This makes sizing unintuitive. box-sizing: border-box fixes it:
/* Default (content-box): total width = 300 + 24 + 24 + 2 + 2 = 352px */
.default {
width: 300px;
padding: 24px;
border: 2px solid;
}
/* border-box: total width = exactly 300px */
.better {
box-sizing: border-box;
width: 300px;
padding: 24px;
border: 2px solid;
}
/* Apply border-box to everything — industry standard */
*, *::before, *::after {
box-sizing: border-box;
}
Warning: Always add *, *::before, *::after { box-sizing: border-box; } at the top of your stylesheet. It prevents dozens of sizing bugs.
Margin collapsing
When two vertical margins meet, they collapse — the larger one survives, not the sum of both:
h2 { margin-bottom: 24px; }
p { margin-top: 16px; }
/* Gap between h2 and p = 24px (not 40px) — larger wins */
/* Collapsing does NOT happen in flexbox or grid containers */
Frequently Asked Questions
What is the difference between padding and margin?
Padding is space inside the element (between content and border). It inherits the element's background colour. Margin is space outside the element (between the border and adjacent elements). It is always transparent.
How do I centre an element horizontally?
For a block element with a set width, use margin: 0 auto. This distributes available space equally on both sides. For flex/grid containers, use justify-content: center instead.
Can I have negative margins?
Yes. Negative margins pull an element in the opposite direction — a negative margin-top pulls the element upward. They are valid CSS and useful for overlapping effects, but use them sparingly.