目標元素寬度 ÷ 父容器寬度 = 百分比寬度
即:percentage = (target_px / context_px) × 100%
假設設計稿:
<div id="wrapper">
<header></header>
<section></section>
<aside></aside>
</div>
固定寬版 CSS:
#wrapper { width: 1000px; }
header { width: 1000px; }
aside { width: 220px; float: left; }
section { width: 770px; float: right; }
#wrapper { width: 98%; max-width: 1000px; margin: 0 auto; } /* 外層彈性,設最大寬防過寬 */
header { width: 100%; } /* 1000 ÷ 1000 = 100% */
aside { width: 22%; float: left; } /* 220 ÷ 1000 = 0.22 = 22% */
section { width: 77%; float: right; } /* 770 ÷ 1000 = 0.77 = 77% */
max-width 防止超寬螢幕過度拉伸.container { width: 90%; max-width: 1200px; margin: 0 auto; }
calc() 處理固定邊距 + 百分比混合.sidebar { width: 220px; }
.content { width: calc(100% - 220px); } /* 完美填滿剩餘空間 */
.card {
padding: 2%; /* 相對父容器寬度 */
margin-bottom: 3%;
}
html { font-size: 100%; } /* 16px 基準 */
h1 { font-size: 2rem; } /* 32px */
p { font-size: 1rem; } /* 16px */
@media (max-width: 768px) {
html { font-size: 87.5%; } /* 14px 基準,全站同步縮放 */
}
.layout {
display: grid;
grid-template-columns: 220px 1fr; /* 固定側邊 + 自適應主區 */
gap: 2%;
}
box-sizing: border-box 全域啟用,寬度包含內距邊框22.2222% 易導致子像素誤差,適度四捨五入(如 22.2%)percentage(220/1000) → 22%postcss-px-to-percentage 自動轉換百分比佈局的本質是「相對關係」而非「絕對數值」。掌握 目標 ÷ 容器 核心公式,配合 box-sizing: border-box、calc()、max-width、現代佈局模組,即能構建真正流體、彈性、可維護的響應式介面。