CSS Basics

CSS Box Model

Master the CSS box model: content, padding, border, margin, and box-sizing.

The CSS Box Model

Every HTML element is a rectangular box. The box model consists of four areas (from inside out):

  1. Content — The actual content (text, images)
  2. Padding — Space inside the border
  3. Border — The border around the padding
  4. Margin — Space outside the border

box-sizing

By default, width/height set the content width only. Use box-sizing: border-box to include padding and border in width/height (much more intuitive).

Always add this to your CSS:

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

Margin Collapse

Vertical margins between adjacent elements collapse to the larger of the two values. This only happens with vertical (top/bottom) margins, not horizontal.

Example

css
/* Box model reset */
*, *::before, *::after {
  box-sizing: border-box;
}

.card {
  /* Content area */
  width: 300px;
  min-height: 200px;

  /* Padding - inside the border */
  padding: 24px;
  /* or shorthand: top/bottom left/right */
  padding: 16px 24px;

  /* Border */
  border: 1px solid #2A2A3A;
  border-radius: 12px;
  border-top: 3px solid #6C5CE7;

  /* Margin - outside the border */
  margin: 16px auto;

  /* Background fills content + padding */
  background: #111118;
}

/* Shorthand order: top right bottom left */
.element {
  padding: 10px 20px 15px 5px;
  margin: 10px 20px;  /* top/bottom left/right */
}

/* Individual sides */
.box {
  margin-top: 24px;
  padding-left: 16px;
  border-bottom: 2px solid #6C5CE7;
}
Try it yourself — CSS