萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS Class 選擇器核心指南:復用性、命名規範、多 Class 組合與現代工程化實踐

Class 選擇器基礎特性

  • 以 . 開頭 (如 .btn)
  • 可重複使用:同一頁面無限次套用
  • 優先級 (0,0,1,0),介於 ID 與元素選擇器之間
  • HTML 寫法: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 選擇器的**超能力**。

命名規範:BEM (Block Element Modifier)

層級語法示例含義
Block.block.card獨立組件根節點
Element.block__element.card__title組件內部子元素
Modifier.block--modifier / .block__element--modifier.card--featured, .card__title--large狀態/變體

多 Class 組合優先級規則

.btn { color: black; }
.btn--primary { color: white; }  /* 同層級,後聲明勝出 */
.btn--danger { color: white !important; }  /* 僅極少數情況用 !important */
  • 同層級類名,**後聲明者勝出** (來源順序)。
  • 建議:**基礎類在前、修飾類在後**,CSS 文件按基礎→變體順序組織。

現代工程化:CSS Modules / Tailwind CSS

CSS Modules (編譯時哈希隔離)

/* Button.module.css */
.base { ... }
.primary { ... }

/* Button.jsx */
import styles from './Button.module.css';
<button className={`${styles.base} ${styles.primary}`}>...</button> 
/* 輸出: 

Tailwind CSS (Utility-First 原子類)

<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,通用設計系統映射為原子類,極致復用。

避坑清單

  1. 避免過度具體化:.sidebar .widget .title → .widget__title
  2. 避免語義模糊:.red, .big → .error-text, .heading-xl
  3. 避免 ID 做樣式:ID 優先級過高,破壞 Class 組合靈活性。
  4. 狀態類統一前綴:.is-active, .is-loading, .has-error (SMACSS 慣例)。

總結

Class 選擇器是 CSS **復用性與組合性的基石**。掌握 BEM 命名、正交組合、現代工程化隔離方案,讓樣式像樂高積木一樣靈活組裝,是前端工程師的核心基本功。

copyright © 萬盛學電腦網 all rights reserved