/* ❌ 糟糕:標籤限定增加特異性,降低復用性 */
ul#nav { }
.menu#sidebar { }
/* ✅ 好:ID 本身唯一,無需標籤限定 */
#nav { }
#sidebar { }
/* ❌ 爛透了:效能極差、強耦合 HTML 結構 */
html div tr td { }
/* ✅ 好:直接語意化類別 */
.table-cell { }
原因:瀏覽器從右向左解析,html div tr td 需向上遍歷 4 層祖先,HTML 結構變動即失效。
/* ❌ 糟糕:冗長、難維護 */
.someclass {
padding-top: 20px;
padding-bottom: 20px;
padding-left: 10px;
padding-right: 10px;
background: #000;
background-image: url(../imgs/carrot.png);
background-position: bottom;
background-repeat: repeat-x;
}
/* ✅ 好:合成屬性一行搞定 */
.someclass {
padding: 20px 10px;
background: #000 url(../imgs/carrot.png) repeat-x bottom;
}
/* ❌ 糟糕:重複聲明 */
.btn-primary { color: #fff; background: #007bff; font-size: 14px; }
.btn-secondary { color: #fff; background: #6c757d; font-size: 14px; }
/* ✅ 好:提取共同部分 */
.btn { color: #fff; font-size: 14px; }
.btn-primary { background: #007bff; }
.btn-secondary { background: #6c757d; }
/* ❌ 糟糕:選擇器擠在一行 */
.selector-a, .selector-b, .selector-c, .selector-d { ... }
/* ✅ 好:多行對齊,易閱讀、易版控 diff */
.selector-a,
.selector-b,
.selector-c,
.selector-d { ... }
/* ✅ 好:複雜值多行對齊 */
.hero {
background-image:
linear-gradient(#000, #ccc),
linear-gradient(#ccc, #ddd);
box-shadow:
2px 2px 2px #000,
1px 4px 1px 1px #ddd inset;
}
| 選擇器類型 | 相對匹配耗時 | 建議 |
|---|---|---|
| ID | 1x(基準) | ✅ 推薦用於唯一區塊 |
| Class | 1.5x | ✅ 主力選擇器 |
| 屬性選擇器 | 2x | ⚠️ 適度使用 |
| 偽類 | 2x | ⚠️ 適度使用 |
| 後代選擇器 | 10x+ | ❌ 禁止(UI CSS) |
| 子選擇器 | 3x | ⚠️ 謹慎使用 |
| 通用選擇器 | 5x | ❌ 避免作為關鍵選擇器 |
.stylelintrc 強制規範stylelint 檢查