The CSS Box Model
Every Element is a Box
In CSS, every HTML element is treated as a rectangular box. This box has four layers from inside to outside:
- Content — the actual text/image
- Padding — space between content and border (inside)
- Border — the outline around the element
- Margin — space outside the border (between elements)
CSS
.box { width: 300px; /* content width */ height: 200px; /* content height */ padding: 20px; /* space inside, all 4 sides */ border: 2px solid #6c63ff; /* border */ margin: 30px; /* space outside, all 4 sides */ background: white; }
Shorthand vs Longhand
CSS
/* Shorthand — all 4 sides same */ p { padding: 20px; } /* Shorthand — vertical horizontal */ p { padding: 10px 20px; } /* top-bottom: 10, left-right: 20 */ /* Shorthand — top right bottom left (clockwise) */ p { padding: 10px 20px 15px 5px; } /* Longhand */ p { padding-top: 10px; padding-right: 20px; padding-bottom: 15px; padding-left: 5px; } /* Same rules apply to margin */
box-sizing — The Most Important Reset
By default (content-box), padding and border are added OUTSIDE the width. This breaks layouts. Always use border-box:
CSS
/* content-box (default) — BAD for layout */ .box { width: 300px; padding: 20px; /* Total actual width = 300 + 20 + 20 = 340px! */ } /* border-box — GOOD, width INCLUDES padding and border */ * { box-sizing: border-box; /* apply to everything */ } .box { width: 300px; padding: 20px; /* Total actual width = 300px exactly. Content shrinks. */ }
Centering with margin: auto
CSS
.container { max-width: 1200px; margin: 0 auto; /* center horizontally — works on block elements */ padding: 0 1.5rem; /* side padding for small screens */ }
Margin Collapse
When two vertical margins touch, they collapse into one (the larger one wins). This only happens vertically:
CSS
h2 { margin-bottom: 30px; } p { margin-top: 20px; } /* Gap between h2 and p = 30px (NOT 50px) — they collapse */ /* Fix: use padding instead, or use flexbox/grid layout */