統一命名慣例是團隊協作、長期維護、自動化工具鏈的基石。本文提供經實戰驗證的 ID/Class 命名字典、檔案架構規範與現代工程化整合指南。
頁面結構區塊 (ID 命名)
| 語意區塊 | ID 命名 | 備註 |
| 頁面容器 | `#container` / `#wrapper` | 最外層包裹,控制最大寬度 |
| 頁首 | `#header` | 含 Logo、主導航 |
| 主內容 | `#main` / `#content` | 核心內容區 |
| 側欄 | `#sidebar` / `#aside` | 輔助內容 |
| 頁尾 | `#footer` | 版權、備案、底部導航 |
| 導航容器 | `#nav` / `#navigation` | 主/次導航統稱 |
功能模組 (Class 命名) - 分類字典
| 分類 | 命名範例 | 覆蓋功能 |
| 品牌/識別 | `.logo`, `.brand`, `.site-title` | Logo、站名、標語 |
| 廣告/推廣 | `.banner`, `.ad`, `.promo`, `.hero` | 輪播、橫幅、英雄區 |
| 導航/選單 | `.nav`, `.menu`, `.subnav`, `.dropdown`, `.tabs`, `.breadcrumb` | 全站/局部導航、麵包層 |
| 表單/互動 | `.form`, `.form-group`, `.field`, `.input`, `.btn`, `.btn-primary`, `.btn-secondary` | 輸入控件、按鈕變體 |
| 內容結構 | `.article`, `.post`, `.entry`, `.card`, `.media`, `.list`, `.item`, `.excerpt` | 文章、卡片、列表項 |
| 資訊回饋 | `.msg`, `.alert`, `.notice`, `.toast`, `.tooltip`, `.modal`, `.tips`, `.error`, `.success` | 通知、提示、彈層 |
| 電商/功能 | `.product`, `.price`, `.cart`, `.checkout`, `.order`, `.filter`, `.sort`, `.pager` | 商品、購物車、篩選、分頁 |
| 社交/關係 | `.profile`, `.avatar`, `.follow`, `.share`, `.comment`, `.rating`, `.vote` | 用戶資料、互動 |
| 版權/法律 | `.copyright`, `.license`, `.privacy`, `.terms` | 頁腳法律資訊 |
狀態與修飾類 (BEM --modifier)
.is-active, .is-hidden, .is-disabled, .is-loading, .is-expanded
.has-error, .has-success, .has-warning
.first, .last, .odd, .even
.current, .selected, .checked
工具類 (Utility/Atomic) - 單一職責
.u-text-center, .u-text-left, .u-text-right
.u-float-left, .u-float-right, .u-clearfix
.u-mt-1, .u-mb-2, .u-p-3 /* 間距刻度 */
.u-d-none, .u-d-block, .u-d-flex /* 顯示控制 */
.u-w-100, .u-max-w-screen-md /* 寬度限制 */
命名鐵律 (必遵)
- **全小寫**:`.user-profile` 非 `.userProfile` 或 `.UserProfile`
- **中劃線分隔**:BEM 規範 `--`、`__`,禁止底線 `_`
- **語意優先**:`.btn-primary` 非 `.btn-red`、`.col-3` 非 `.width-300px`
- **不縮寫**:`.navigation` 非 `.nav` (除非極高頻)、`.button` 非 `.btn` (團隊約定除外)
- **避免標籤綁定**:`.header-nav` 非 `header .nav` (提高可移植性)
CSS 檔案架構組織
styles/
├── core/
│ ├── reset.css /* Normalize/Reset */
│ ├── variables.css /* Custom Properties (Design Tokens) */
│ ├── typography.css /* 字體、標題、行高 */
│ └── layout.css /* Grid/Flex 佈局骨架 */
├── components/
│ ├── button.css
│ ├── card.css
│ ├── form.css
│ ├── modal.css
│ └── nav.css
├── modules/
│ ├── header.css
│ ├── footer.css
│ ├── sidebar.css
│ └── hero.css
├── pages/
│ ├── home.css
│ ├── article.css
│ └── checkout.css
├── utilities/
│ ├── spacing.css
│ ├── visibility.css
│ └── print.css
└── main.css /* 統一入口,依序 @import */
現代工程化整合
- Stylelint:`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 Modules / Scoped CSS:編譯期自動哈希,物理隔離命名衝突
- Design Tokens (Style Dictionary):色彩、間距、字體集中定義 → 輸出 CSS Variables、JS/TS/JSON/Swift/Kotlin
- Tailwind/UnoCSS:工具類優先,HTML 內直接組合,減少命名決策疲勞
- Storybook:元件驅動開發,視覺化驗證命名與樣式一致性