The Box Model
Every element is rendered as a rectangular box with four layers:
┌─────────────────────────────┐ ← margin
│ ┌───────────────────────┐ │ ← border
│ │ ┌─────────────────┐ │ │ ← padding
│ │ │ content │ │ │
│ │ └─────────────────┘ │ │
│ └───────────────────────┘ │
└─────────────────────────────┘.box {
width: 300px;
padding: 20px; /* space inside border */
border: 2px solid #333;
margin: 16px; /* space outside border */
}box-sizing
By default (content-box), width/height applies to content only — padding and border add to the total size. Use border-box to include them:
*, *::before, *::after {
box-sizing: border-box; /* always do this */
}
.box {
width: 300px; /* now total width = 300px including padding + border */
padding: 20px;
border: 2px solid #333;
}Shorthand
/* All sides equal */
margin: 16px;
/* Top/bottom | Left/right */
padding: 12px 24px;
/* Top | Right | Bottom | Left (clockwise) */
margin: 8px 16px 24px 16px;Always add
box-sizing: border-box to * at the top of your stylesheet — it makes layout math much simpler.