CSSCSS · Lesson 3 of 9

The Box Model

Every HTML element is a box. This sounds obvious until you try to center something, and then it sounds like a conspiracy.

The CSS box model defines how the browser calculates the size and spacing of every element. From inside out: content → padding → border → margin. Understanding this model is the key to understanding layout.

CSS
/* Box model components */
.box {
  /* Content area */
  width: 300px;
  height: 200px;

  /* Padding — space inside the border */
  padding: 20px;                  /* all sides */
  padding: 10px 20px;             /* vertical horizontal */
  padding: 10px 20px 15px 20px;   /* top right bottom left */

  /* Border */
  border: 2px solid #333;
  border-radius: 8px;             /* rounded corners */
  border-top: 4px solid blue;     /* individual sides */

  /* Margin — space outside the border */
  margin: 0 auto;                 /* 0 top/bottom, auto left/right = centered */
  margin-bottom: 16px;
}

/* CRITICAL: Use border-box sizing */
/* Without it, padding and border ADD to the width */
/* With it, padding and border are INCLUDED in the width */
* {
  box-sizing: border-box;  /* Put this in every project. Always. */
}

/* Display types */
.block {
  display: block;      /* Takes full width, starts new line (default for div, p, h1) */
}
.inline {
  display: inline;     /* Flows with text, no width/height (default for span, a) */
}
.inline-block {
  display: inline-block; /* Flows inline, but accepts width/height */
}
.hidden {
  display: none;       /* Completely removed from layout */
}
.invisible {
  visibility: hidden;  /* Hidden but still takes up space */
}
CSS
/* The centering problems and solutions */

/* Center block element horizontally */
.centered-block {
  width: 500px;
  margin: 0 auto;    /* auto left+right = equal margins = centered */
}

/* Center with Flexbox (see next lesson) */
.center-flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Overflow */
.overflow-demo {
  width: 200px;
  height: 100px;
  overflow: hidden;   /* clip overflow */
  overflow: scroll;   /* always show scrollbar */
  overflow: auto;     /* scrollbar only when needed */
  overflow-x: auto;   /* horizontal only */
}

/* Position */
.positioned {
  position: static;    /* default — in document flow */
  position: relative;  /* offset from its normal position */
  position: absolute;  /* removed from flow, positioned relative to nearest non-static ancestor */
  position: fixed;     /* relative to viewport, stays while scrolling */
  position: sticky;    /* relative until it hits a threshold, then fixed */
  top: 10px;
  left: 20px;
  z-index: 10;         /* stack order (higher = on top) */
}
⚠ Warning
Add box-sizing: border-box to every project, globally. Without it, a box with width: 300px and padding: 20px will actually be 340px wide — a constant source of confusion. The * { box-sizing: border-box; } rule is a near-universal best practice.