. 開頭 (如 .btn)(0,0,1,0),介於 ID 與元素選擇器之間class="btn btn-primary" (空格分隔多類)/*** 基礎按鈕 ***/
.btn {
display: inline-flex;
align-items: center;
padding: 0.5rem 1rem;
border-radius: 4px;
font-weight: 500;
transition: background 0.2s;
}
/*** 變體修飾符 ***/
.btn--primary { background: #0066cc; color: #fff; }
.btn--secondary { background: #fff; color: #0066cc; border: 1px solid #0066cc; }
.btn--danger { background: #dc3545; color: #fff; }
/*** 尺寸修飾符 ***/
.btn--sm { padding: 0.25rem 0.5rem; font-size: 0.875rem; }
.btn--lg { padding: 0.75rem 1.5rem; font-size: 1.125rem; }
/*** HTML 組合使用 ***/
<button class="btn btn--primary btn--lg">主要大按鈕</button>
<button class="btn btn--secondary btn--sm">次要小按鈕</button>
單一職責、正交組合、指數級變體 — 這是 Class 選擇器的**超能力**。
| 層級 | 語法 | 示例 | 含義 |
|---|---|---|---|
| Block | .block | .card | 獨立組件根節點 |
| Element | .block__element | .card__title | 組件內部子元素 |
| Modifier | .block--modifier / .block__element--modifier | .card--featured, .card__title--large | 狀態/變體 |
.btn { color: black; }
.btn--primary { color: white; } /* 同層級,後聲明勝出 */
.btn--danger { color: white !important; } /* 僅極少數情況用 !important */
/* Button.module.css */
.base { ... }
.primary { ... }
/* Button.jsx */
import styles from './Button.module.css';
<button className={`${styles.base} ${styles.primary}`}>...</button>
/* 輸出:
<button class="px-4 py-2 rounded bg-blue-600 text-white font-medium hover:bg-blue-700 focus:ring-2 focus:ring-blue-500">...</button>
零自定義 CSS,通用設計系統映射為原子類,極致復用。
.sidebar .widget .title → .widget__title.red, .big → .error-text, .heading-xl.is-active, .is-loading, .has-error (SMACSS 慣例)。Class 選擇器是 CSS **復用性與組合性的基石**。掌握 BEM 命名、正交組合、現代工程化隔離方案,讓樣式像樂高積木一樣靈活組裝,是前端工程師的核心基本功。