掌握這八大技巧,能讓你的 CSS 佈局開發效率翻倍、Bug 率大幅下降。本文結合現代最佳實踐,重新詮釋經典技巧並補充現代方案。
validator.w3.org) 或編輯器插件 (HTMLHint, Webhint) 實時檢查語法、巢狀、屬性合法性jigsaw.w3.org/css-validator) 檢查語法錯誤、未知屬性、廢棄用法/* 1. 額外標籤法 (語義差,不推薦) */
.clear { clear: both; height: 0; overflow: hidden; }
/* 2. 偽元素 Clearfix (經典通用) */
.clearfix::after {
content: '';
display: table; /* 或 block */
clear: both;
}
/* 3. 父級觸發 BFC (現代推薦) */
.parent {
overflow: hidden; /* 簡單但會剪裁陰影/絕對定位子元素 */
/* 或 */
display: flow-root; /* 現代標準,無副作用,IE 不支持 */
/* 或 */
display: flex; /* 兼容性佳,副作用最小 */
/* 或 */
display: grid;
}
/* Float 時代三列佈局 */
.col { float: left; width: 33.33%; }
.clearfix::after { content: ''; display: table; clear: both; }
/* Flex 時代 */
.row { display: flex; gap: 20px; }
.col { flex: 1; }
/* Grid 時代 */
.grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }
/* 避免父子 margin 合併:父級觸發 BFC */
.parent { overflow: hidden; } /* 或 display: flow-root; flex; grid; */
/* 避免兄弟合併:插入 1px padding/border 或空 div */
.divider { height: 0; border-top: 1px solid transparent; }
/* 利用合併:組件間距系統化 */
.section { margin-bottom: 32px; }
.section:last-child { margin-bottom: 0; }
/* 相鄰 section 間距自動取 32px 而非 64px */
.box {
width: 300px;
padding: 20px;
border: 5px solid #333;
/* 標準盒模型:實際佔寬 = 300 + 40 + 10 = 350px */
/* IE 怪異模型:實際佔寬 = 300px (含 padding/border) */
}
*, *::before, *::after {
box-sizing: border-box; /* width/height 包含 padding+border */
}
/* 現在 .box 實際佔寬 = 300px,內容區 = 300 - 40 - 10 = 250px */
.parent { width: 300px; padding: 20px; }
.child { margin: 10px; } /* 不設 width,自動填滿父級 content-box */
現代瀏覽器全支持,但理解歷史替代方案有助於理解佈局邏輯:
/* IE6/7 模擬 min-width */
.container {
width: expression(document.body.clientWidth < 800 ? "800px" : "auto"); /* CSS Expression, 性能極差,禁用 */
}
/* 現代:直接用 */
.container { min-width: 800px; width: 100%; }
現代項目直接使用 min/max-width/height,配合 Flex/Grid 內在自適應特性,極少需要顯式 min/max。
/* 經典 50%+50% 可能因浮點誤差變 100.1% 導致換行 */
.col { width: 49.9%; float: left; } /* 留 0.2% 間隙 */
/* 現代:Flex/Grid 精確分配,無浮點誤差 */
.row { display: flex; }
.col { flex: 1; } /* 自動均分,永不超出 100% */
/* Grid 精確分數單位 */
.grid { display: grid; grid-template-columns: 1fr 1fr; }
/* 簡寫屬性順序統一為 TRBL */
margin: 10px 20px 30px 40px; /* 上右下左 */
padding: 10px 20px 30px 40px;
border-width: 1px 2px 3px 4px;
border-color: red green blue yellow;
border-radius: 4px 8px 12px 16px; /* 左上、右上、右下、左下 */
box-shadow: 2px 4px 6px 8px; /* x-offset y-offset blur spread */
/* 記憶口訴:「TRouBLe」 = Top Right Bottom Left */
| 屬性類型 | 必須帶單位 | 可無單位 (值為 0) | 特殊無單位值 |
|---|---|---|---|
| 長度 | px, rem, em, %, vw, vh... | 0 | - |
| 時間 | s, ms | 0 | - |
| 角度 | deg, rad, turn | 0 | - |
| line-height | px, rem, em, % | - | 數字 (倍數) line-height: 1.5 |
| opacity | - | - | 純數字 0-1 |
| transform | translate(10px) rotate(45deg) | translate(0) | - |
| flex/grid | fr, %, px... | 0 | flex: 1 (無單位 = flex-grow) |
@media (min-width: ...) 逐層增強