</>HTML & CSS
IntermediateLesson 6 of 15

The Box Model – HTML & CSS

Content, padding, border, margin, box-sizing and display.

Every element is a rectangular box made of four layers: content, padding (inner spacing), border and margin (outer spacing). By default (box-sizing: content-box), width and height refer only to the content – padding and border are added on top.

<!DOCTYPE html>
<style>body{font:16px system-ui,sans-serif;margin:12px;background:#fff;color:#222}
.box { width: 200px; padding: 20px; border: 5px solid #333; margin: 10px 0; background: #9cf; }
.border-box { box-sizing: border-box; }
</style>
<div class="box" id="a">content-box</div>
<div class="box border-box" id="b">border-box</div>
<p id="info"></p>
<script>
info.textContent = 'a: ' + a.offsetWidth + 'px (200 + 2*20 + 2*5)   b: ' + b.offsetWidth + 'px';
</script>

That is why almost all projects set *, *::before, *::after { box-sizing: border-box; }: then width is the actual total width including padding and border. Shorthand values are read clockwise: margin: top right bottom left. Two values = top/bottom and left/right; margin: 0 auto centers a block with a fixed width.

<!DOCTYPE html>
<style>body{font:16px system-ui,sans-serif;margin:12px;background:#fff;color:#222}
*, *::before, *::after { box-sizing: border-box; }
.karte { max-width: 260px; margin: 0 auto; padding: 16px 20px; border: 1px solid #ccc;
         border-radius: 12px; box-shadow: 0 4px 12px rgb(0 0 0 / 15%); }
.karte h3 { margin: 0 0 8px; }
.karte p { margin: 0; color: #555; }
</style>
<div class="karte">
  <h3>Centered Card</h3>
  <p>max-width, margin auto, padding, border, radius and shadow.</p>
</div>

The behavior depends on display: block (own line, full width, width/height take effect), inline (flows within text, width/height have no effect, vertical margins do not work) and inline-block (flows, but sizes take effect). Touching vertical margins of blocks collapse to the larger value.

<!DOCTYPE html>
<style>body{font:16px system-ui,sans-serif;margin:12px;background:#fff;color:#222}
span.a, span.b { background: #fd9; padding: 10px 14px; margin: 20px; }
span.b { display: inline-block; width: 90px; height: 40px; }
.oben { margin-bottom: 30px; background: #cfc; }
.unten { margin-top: 20px; background: #fcc; }
</style>
<p>Inline: <span class="a">Span A</span> (vertical spacing has no effect)</p>
<p>Inline-Block: <span class="b">Span B</span> (height takes effect)</p>
<div class="oben">Top: margin-bottom 30px</div>
<div class="unten">Bottom: margin-top 20px – gap between is only 30px, not 50px</div>
WarningMargin collapsing only happens with vertical margins of block elements in normal flow – not with Flexbox/Grid items and not with horizontal margins. This explains many "aha" moments ("why is the gap not twice as big?").
TipOpen the DevTools and look at the colored box-model diagram in the "Computed" tab: it shows the content, padding, border and margin of the selected element to scale.