NelsonLabs
CSS Styling/The Box Model

The Box Model

Every single HTML element is a box. Understanding how that box works โ€” its content, padding, border, and margin โ€” is the most foundational skill in CSS layout.

ANALOGY

Think of a framed photograph. The photo itself is the content. The mat (white border inside the frame) is padding โ€” space between the content and the frame edge. The frame is the border. The space between your framed photo and the next thing on the wall is margin. Stack these boxes and you have a web page.

The box model properties
css
div {
  /* Content */
  width: 300px;
  height: 200px;

  /* Padding โ€” space inside, between content and border */
  padding: 20px;              /* all sides */
  padding: 10px 20px;         /* top/bottom  left/right */
  padding: 10px 20px 15px 5px; /* top right bottom left */

  /* Border โ€” the outline */
  border: 2px solid #2E2A22;
  border-radius: 8px;         /* rounds corners */

  /* Margin โ€” space outside, between this element and others */
  margin: 0 auto;             /* 0 top/bottom, auto left/right = centred */
}

box-sizing: border-box

By default, width controls only the content area. Padding and border are added on top, making elements wider than you'd expect. This is confusing. box-sizing: border-box changes the model so padding and border are included in the width โ€” much more intuitive.

Always use border-box
css
/* Apply this to every project โ€” it prevents layout headaches */
*, *::before, *::after {
  box-sizing: border-box;
}

/* Now this div is exactly 300px wide including its padding */
div {
  width: 300px;
  padding: 20px;  /* included in the 300px, not added on top */
}

display property

Block vs inline vs inline-block
css
/* Block โ€” takes full width, starts on new line */
div, p, h1, section { display: block; }

/* Inline โ€” sits within text, ignores width/height */
span, a, strong, em { display: inline; }

/* Inline-block โ€” sits in text but respects width/height */
.badge { display: inline-block; padding: 4px 8px; }

/* Hide an element completely */
.hidden { display: none; }