累積實戰經驗提煉的 6 大技巧,涵蓋縮寫、多重 Class、單位、大小寫、浮動清除、inline-block 空白,每一招都能即刻應用。
/* 邊框縮寫 */
border: 1px solid #ccc; /* 替代 4 行 border-top/right/bottom/left */
/* 外距/內距縮寫:順序 上 右 下 左 (順時針) */
margin: 10px 20px 30px 40px;
/* 2 值:上下 | 左右 */
margin: 10px 20px;
/* 3 值:上 | 左右 | 下 */
margin: 10px 20px 30px;
/* 1 值:四邊相同 */
margin: 10px;
/* 字體縮寫:font-style | font-variant | font-weight | font-size/line-height | font-family */
font: italic small-caps bold 1rem/1.5 system-ui, sans-serif;
/* 背景縮寫 */
background: #fff url(bg.png) no-repeat center / cover; /* color image repeat position/size */
注意:數值與單位間不可有空格(10 px ❌ → 10px ✅)。
.a { color: red; font-weight: bold; }
.b { background: yellow; padding: 0.5em; }
<p class="a b">同時擁有紅字加粗 + 黃底內距</p>
.btn .btn-primary .btn-lg),而非單一巨大類別。width: 100; height: 50; font-size: 12;(無單位視為無效,瀏覽器忽略)。width: 100px; height: 50px; font-size: 12px; 或 1.2rem、1.5em、100%。margin: 0; padding: 0; — 0px = 0em = 0% = 0。rem(根元素相對)、em(父元素相對)、%(容器相對),px 僅用於邊框、陰影、極小固定尺寸。class/id 值規範上區分(瀏覽器多不區分,但勿依賴)。class/id、屬性值嚴格區分大小寫。.nav-item, #main-content)。#aaa { border:1px solid #ccc } 配合 id="aaa" 生效;id="AAA" 在 XHTML/XML 失效。| 方法 | 代碼 | 優點 | 缺點 |
|---|---|---|---|
| 父層 overflow | .parent { overflow: hidden; } |
無額外標籤、代碼極少 | 會切掉陰影/絕對定位溢出內容 |
| 父層浮動 | .parent { float: left; width: 100%; } |
包含浮動、無溢出切割 | 父層也脫離文檔流,需向上傳遞清除 |
| 偽元素 Clearfix | .clearfix::after { content:""; display:block; clear:both; } |
不影響佈局、通用性最強 | 需額外類別、IE6/7 需 zoom:1 |
| 現代:display: flow-root | .parent { display: flow-root; } |
原生、語意明確、無副作用 | IE/舊 Edge 不支援 |
成因:HTML 換行/縮進被渲染為文字節點(空白字元),佔據約 4px(依字體大小)。
| 解法 | 代碼 | 優缺點 |
|---|---|---|
父層 font-size: 0 |
.parent { font-size: 0; } .child { font-size: 1rem; } |
✅ 徹底解決;⚠️ 子層必須重設 font-size,巢狀複雜時難維護 |
| HTML 註解/無換行 | <ul><li>A</li><!--><li>B</li></ul> |
✅ 無 CSS 修改;❌ 代碼可讀性極差、格式化工具會破壞 |
| 負 margin | .child { margin-left: -4px; } |
✅ 簡單;❌ 需精確計算、字體/瀏覽器不同值不同、極不穩定 |
| 現代:Flex/Grid 取代 | .parent { display: flex; gap: 0.5rem; } |
✅ 根治間隙、語意化、響應式、對齊控制豐富 |
掌握這 6 招,CSS 代碼即刻更精簡、更相容、更專業。