Beginner
+25 XP

👋 Start learning JavaScript right now — for free!

📖

Box Model and Display

margin, padding, border and how they affect element size

📦

Box Model — every element is a box

Every HTML element is a rectangular box with four layers: 1. **Content** — the content (text, images) 2. **Padding** — inner space between content and border 3. **Border** — the border around the padding 4. **Margin** — outer space from other elements Like a gift: text on a card (content) → foam padding (padding) → box (border) → empty space to the next item (margin).

css
💬

Shorthand with spaces: one value = all sides, two = top/bottom and right/left, four = top clockwise.

box-sizing: border-box — the most important rule

Problem without border-box:

css
.box { width: 300px; padding: 20px; border: 2px solid; }
/* Actual width = 300 + 20*2 + 2*2 = 344px — unexpected! */

Solution — border-box:

css
* { box-sizing: border-box; }
.box { width: 300px; padding: 20px; border: 2px solid; }
/* Actual width = 300px — padding and border are inside */

With border-box the width you set is the width you get. Always add this rule!

display — the block type

  • block — takes the full line width, a full block (div, p, h1)
  • inline — takes only the content width, no width/height (span, a, strong)
  • inline-block — like inline, but you can set width/height
  • none — hides the element completely

Margin collapse: when two block elements are stacked vertically — their top and bottom margins merge into one (the larger one). For example, margin-bottom: 20px on a p and margin-top: 30px on the next p gives 30px of space, not 50px. Fix: use margin only on the bottom or only on the top.

css
💬

max-width: 1200px + margin: 0 auto — the standard pattern for a centred container.

Comments

Log In or Start to leave a comment.