/* ❌ 差:標簽限定,提高特定度,降低復用 */
ul#nav { }
.menu#sidebar { }
/* ✅ 好:ID 本身唯一,無需標簽限定 */
#nav { }
#sidebar { }
/* ❌ 爛透了:緊耦合 HTML 結構,效能低,極難維護 */
html body div header nav ul li a { }
/* ✅ 好:扁平化,語意化 class */
.nav-link { }
**原則**:選擇器嵌套 **不超過 3 層**,優先用單一 class 直接命中。
/* ❌ 差:過度限定,降低復用,增加匹配成本 */
button.primary { }
span.icon { }
.content .btn.primary { }
/* ✅ 好:單一職責 class */
.btn { }
.btn--primary { }
.icon { }
/* ❌ 冗長 */
.box {
padding-top: 20px;
padding-right: 10px;
padding-bottom: 20px;
padding-left: 10px;
background-color: #000;
background-image: url(img.png);
background-position: bottom;
background-repeat: repeat-x;
}
/* ✅ 簡潔 */
.box {
padding: 20px 10px;
background: #000 url(img.png) repeat-x bottom;
}
**常用簡寫**:`margin`、`padding`、`border`、`border-radius`、`background`、`font`、`flex`、`grid`、`animation`、`transition`。
/* ❌ 重複 */
.btn-primary { color: #fff; background: #3498db; padding: 0.5rem 1rem; }
.btn-secondary { color: #fff; background: #95a5a6; padding: 0.5rem 1rem; }
/* ✅ 提取公共 */
.btn { padding: 0.5rem 1rem; color: #fff; border-radius: 4px; }
.btn--primary { background: #3498db; }
.btn--secondary { background: #95a5a6; }
.component {
/* 1. 佈局/定位 */
position: relative;
display: flex;
z-index: 10;
/* 2. 盒模型 */
width: 100%;
padding: 1rem;
margin-bottom: 1rem;
/* 3. 視覺/裝飾 */
background: #fff;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,.1);
/* 4. 文字/排版 */
font-size: 1rem;
line-height: 1.5;
color: #333;
/* 5. 動畫/過渡 */
transition: box-shadow 0.2s;
/* 6. 其他 */
cursor: pointer;
}
**理由**:瀏覽器渲染管線順序大致為 佈局 → 繪製 → 合成,按此順序閱讀/編寫符合心智模型。
.rounded {
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
/* 值垂直對齊,易於比對與批量編輯 */
}
.parent {
.child {
color: red;
}
}
/* ❌ 擠在一行 */
.btn-primary, .btn-secondary, .btn-tertiary { }
/* ✅ 各自一行,易讀、易 Git diff */
.btn-primary,
.btn-secondary,
.btn-tertiary { }
.selector {
property: value;
}
.good {
color: red;
background: blue;
}
防止後續添加屬性時忘記補分號導致語法錯誤。
/* ===================================
模塊:按鈕組件
=================================== */
/* 基礎樣式 ----------------------------------- */
.btn { ... }
/* 變體:主要按鈕 ----------------------------- */
.btn--primary { ... }
/* 狀態:禁用 --------------------------------- */
.btn:disabled { ... }
/* package.json */
{
"devDependencies": {
"stylelint": "^16",
"stylelint-config-standard": "^36",
"stylelint-config-recess-order": "^5", /* 聲明排序 */
"stylelint-prettier": "^4"
},
"scripts": {
"lint:css": "stylelint \"**/*.css\" --fix"
}
}
/* .stylelintrc.json */
{
"extends": ["stylelint-config-standard", "stylelint-config-recess-order"],
"plugins": ["stylelint-prettier"],
"rules": {
"prettier/prettier": true,
"selector-class-pattern": "^[a-z][a-z0-9]*(-[a-z0-9]+)*(__[a-z0-9]+(-[a-z0-9]+)*)?(--[a-z0-9]+(-[a-z0-9]+)*)?$" /* BEM 強制 */
}
}
好的 CSS 規範不是束縛,而是**自由的前提**:統一風格減少認知負荷,扁平選擇器提升效能與復用,簡寫屬性縮減體積,聲明分組對齊渲染管線,工具鏈守護底線。建立團隊共識,接入 CI/CD,讓規範成為肌肉記憶而非負擔。