CSS 看似簡單,但隨著專案增長,雜亂的代碼會拖垮效能與維護效率。以下 13 條鐵律,涵蓋架構、命名、寫法、效能、部署全流程,助你產出專業級樣式表。
錯誤:* { margin:0; padding:0; } — 影響所有元素(含 button、input 等表單原生外觀),效能差。
建議:參考 Normalize.css 或 Eric Meyer Reset 2.0,僅重置專案用到的元素,並保留有用的預設值(如 sup/sub 字體縮放)。
.red, .leftBar, .bigFont — 顏色/位置/大小改變時類別名失去意義。.primary-btn, .sidebar, .post-wrap — 反映元件角色,樣式變更不影響 HTML。.text-center, .d-flex, .sr-only 等單一用途類別可用表象命名,因為不會改變用途。/* 冗長 */
li {
font-family: Arial, Helvetica, sans-serif;
font-size: 1.2em;
line-height: 1.4em;
padding-top: 5px;
padding-bottom: 10px;
padding-left: 5px;
}
/* 縮寫 */
li {
font: 1.2em/1.4em Arial, Helvetica, sans-serif;
padding: 5px 0 10px 5px; /* 上 右 下 左 */
}
常用縮寫:margin, padding, border, font, background, 顏色值(#fff = #ffffff)。
/* 重複 */
#container li { font-family: Georgia, serif; }
#container p { font-family: Georgia, serif; }
#container h1 { font-family: Georgia, serif; }
/* 繼承 */
#container { font-family: Georgia, serif; }
可繼承屬性:color, font-*, line-height, text-align, list-style 等。
/* 分散 */
h1 { font-family: Arial; font-weight: normal; }
h2 { font-family: Arial; font-weight: normal; }
h3 { font-family: Arial; font-weight: normal; }
/* 合併 */
h1, h2, h3 { font-family: Arial; font-weight: normal; }
/*------------------------------------
1. Reset & Base
2. Layout (Header, Content, Sidebar, Footer)
3. Modules (Buttons, Cards, Forms)
4. State (Active, Disabled, Hidden)
5. Theme / Overrides
----------------------------------- */
/*** Header ***/
#header { ... }
/*** Content ***/
#content { ... }
#content .post { ... }
推薦邏輯分組:
定位/盒模型 → 字體/文字 → 視覺/背景 → 動畫/其他
範例:
.card {
/* 定位/盒模型 */
display: flex;
position: relative;
width: 300px;
height: 200px;
margin: 1rem auto;
padding: 1rem;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,.1);
/* 字體/文字 */
font: 1rem/1.5 system-ui, sans-serif;
color: #333;
text-align: left;
/* 視覺/背景 */
background: #fff;
overflow: hidden;
/* 動畫 */
transition: transform .2s, box-shadow .2s;
}
.tag { color: red; font-weight: bold; }。| 不推薦 | 推薦 | 原因 |
|---|---|---|
border: 0 | border: none | none 完全跳過邊框渲染,0 仍保留寬度/顏色計算 |
visibility: hidden | display: none | display:none 不佔版面、不渲染、不佔記憶體 |
@import | <link> | @import 串列載入、阻塞渲染、不屬 HTML 標準 |
<link>)width: expression(...) 會在滾動、縮放、移動滑鼠時高頻重算(輕鬆萬次/秒),嚴重拖慢頁面。非必要禁用;若必須用,改用 JS 事件監聽器。
source map 方便線上除錯。將 CSS 分層:
Settings → Tools → Generic → Elements → Objects → Components → Utilities
每層權重遞增,依賴關係單向,避免循環依賴與權重戰爭。
遵循這 13 條鐵律,你的 CSS 將具備高可讀性、低耦合、好擴展、快渲染、易部署的專業素質。