CSS 百分比值**不是絕對單位**,它必須相對某個「參照值」計算為絕對值才生效。參照值因屬性而異,是理解百分比行為的關鍵。
| 屬性 | 參照基準 | 備註 |
|---|---|---|
| width / height | 包含塊的 width / height | 包含塊通常為父元素 content box;absolute 定位時為最近定位祖先的 padding box |
| margin / padding(四個方向) | **包含塊的 width** | **關鍵**:垂直方向也參照寬度!非 height |
| border-radius | 元素自身的 width / height | 50% 即圓形/橢圓;水平/垂直半徑分別參照自身高/寬 |
| background-position | (容器尺寸 - 圖片尺寸) × 百分比 | 可為負值;50% 50% = 置中 |
| font-size | 父元素 font-size | 繼承鏈傳遞 |
| line-height | **自身 font-size** | 非父元素!1.5 = 1.5 × 自身 font-size |
| vertical-align | **自身 line-height** | 10% = 0.1 × line-height |
| top / bottom | 包含塊的 height | 定位元素專用 |
| left / right | 包含塊的 width | 定位元素專用 |
| transform: translate() | **元素自身 border-box 尺寸** | translate(50%, 50%) = 位移自寬/高一半 |
| transform: translate3d() | X/Y 同 translate,Z **不支援百分比** | Z 軸無參照基準 |
<div class="parent">
<div class="child">高度 100%?</div>
</div>
.parent { height: auto; } /* 無固定高度 */
.child { height: 100%; } /* ❌ 無效,等同 auto */
規範規定:若包含塊高度**由內容決定**(auto),且子元素**非絕對定位**,則 `height: %` 視為 `auto`。
解決方案:
為什麼不參照 height?
.aspect-ratio-box {
width: 50%;
padding-top: 50%; /* 利用這特性做 1:1 或 16:9 響應式比例盒 */
position: relative;
}
.aspect-ratio-box > .content {
position: absolute; inset: 0;
}
.circle {
width: 100px; height: 100px;
border-radius: 50%; /* 水平半徑 = 50% width = 50px,垂直半徑 = 50% height = 50px → 正圓 */
}
.ellipse {
width: 200px; height: 100px;
border-radius: 50%; /* 水平 100px,垂直 50px → 橢圓 */
}
/* 等同於 */
.ellipse { border-radius: 100px / 50px; } /* 明確指定水平/垂直半徑 */
`background-position: 50% 50%` 不是「圖片中心對齊容器中心」,而是:
實際偏移 = (容器尺寸 - 圖片尺寸) × 百分比
/* 例:容器 300px,圖片 100px,50% → (300-100)×0.5 = 100px */
圖片左邊緣在容器 100px 處 → 圖片中心 (100+50=150) 對齊容器中心 (150) ✓
這設計使得「百分比語意與視覺直覺一致」。
.parent {
font-size: 16px;
line-height: 150%; /* 計算值 = 24px */
}
.child {
font-size: 20px; /* 繼承到的 line-height 是 24px(絕對值),而非 150% */
/* 導致 child 行高變小,文字擠壓 */
}
規則:百分比值在**指定值階段**就按參照值計算為絕對長度,**計算值**為絕對單位,**繼承的是計算值**,而非百分比本身。
解決:用無單位數值 `line-height: 1.5`(繼承係數,子元素按自已 font-size 重算),或显式重設 `line-height`。
aspect-ratio: 16 / 9:直接聲明寬高比,替代 padding-top hackclamp(min, preferred%, max):流體排版/間距,無需媒體查詢container-query:`@container (width > 50%)` 元件級百分比響應relative color syntax:`rgb(from var(--color) r g b / 50%)` 色彩透明度百分比CSS 百分比值是「建立元素間關聯」的強大膠水。精通**每個屬性的參照基準**、**繼承時的計算值轉換**、**垂直百分比參照寬度的設計邏輯**,並善用現代特性(aspect-ratio、clamp、container queries)替代舊式 hack,即可寫出真正彈性、可維護、響應式的樣式代碼。