← HTML / CSS Course

CSS CORE · 48

Box Model / Units / Typography:畫面上的尺寸到底怎麼算

CSS layout 的大量 bug 都能先回到 box model:content、padding、border、margin,再加上 containing block、intrinsic size 與 overflow。

Learning outcomes

1. Box model

.card {
  width: 320px;
  padding: 24px;
  border: 2px solid;
  margin: 16px;
}
content+ paddinginside border+ borderborder box+ marginouter spacing

2. box-sizing

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

border-box 讓 declared width 包含 padding/border,更容易控制 layout。但 margin 仍在盒子外。

3. Units 是 reference frame

UnitReference
pxCSS pixel
%依 property 相對 containing block 等 context
remroot font size
vw/vhviewport
ch約字元寬度,常用於 readable text measure

4. Fluid constraints 比固定寬度更耐用

.page {
  width: min(
    100% - 2rem,
    70rem
  );
  margin-inline: auto;
}

.prose {
  max-width: 70ch;
}

5. Typography 影響 layout

body {
  font-size: 1rem;
  line-height: 1.6;
}

h1 {
  font-size:
    clamp(2rem, 5vw, 4rem);
  line-height: 1.05;
}

文字不是最後才「裝飾」;line-height、measure、font size 都會改 element intrinsic dimensions。

Project checkpoint:Course Profile v5

.profile {
  width:
    min(100% - 2rem, 72rem);
  margin-inline: auto;
}

.card {
  padding: 1.25rem;
  border: 1px solid #d9e2ed;
  border-radius: 1rem;
}

.card p {
  max-width: 65ch;
}

Debug evidence:橫向捲軸從哪來

先在 DevTools 看是哪個 element border box 超出 viewport,再檢查 fixed width、padding、long unbreakable content、absolute/fixed positioning;不要直接全站加 overflow-x:hidden 把證據藏掉。

Knowledge check

  1. content-box width=300 + padding 20x2 + border 2x2,border box 多寬?
  2. 為什麼文字行寬常用 max-width/ch?
  3. 做一個故意 overflow 的卡片,再用 DevTools 找 root cause。
  4. 把固定 960px container 改成 fluid + max constraint。