The CSS Box Model

๐Ÿ“š Lesson 4 of 30  โ€ข  โฑ 10 min read  โ€ข  Beginner

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:

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 */