萬盛學電腦網

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

CSS ID 選擇器完整指南:唯一性約束、派生選擇器基石、特異性陷阱與現代替代方案

ID 選擇器語法與唯一性約束

<!-- HTML: id 在頁面中唯一 -->
<header id="site-header">...</header>
<main id="main-content">...</main>
<footer id="site-footer">...</footer>

/* CSS: # 開頭 */
#site-header { border-bottom: 1px solid #eee; }
#main-content { padding: 2rem; }
#site-footer { background: #f5f5f5; }

HTML 標準強制:同一頁面 id 值必須唯一。違反會導致:

  • JS document.getElementById() 只返回第一個
  • 錨點連結 href="#id" 行為不可預測
  • 無障礙樹結構錯誤 (ARIA 關聯失效)
  • W3C 驗證失敗

ID 選擇器三大核心用法

1. 頁面級唯一區塊樣式 (佈局骨架)

#header { position: sticky; top: 0; z-index: 100; }
#main { display: grid; grid-template-columns: 1fr 300px; gap: 2rem; }
#footer { margin-top: auto; }

2. 派生選擇器基石 (範圍限定)

/* 限定在 #sidebar 內的所有段落 */
#sidebar p { font-size: 0.875rem; line-height: 1.6; }

/* 限定在 #main 內的標題 */
#main h2 { border-bottom: 2px solid var(--color-primary); padding-bottom: 0.5rem; }

3. JavaScript 掛鉤 (行為與樣式分離)

<button id="submit-btn" class="btn btn--primary">提交</button>

/* CSS 不用 #submit-btn 定義樣式 */
/* JS 使用 */
const btn = document.getElementById('submit-btn');
btn.addEventListener('click', handleSubmit);

特異性陷阱:ID 權重過高 (0,1,0,0)

/* ❌ 反模式:ID 用於樣式,導致難以覆蓋 */
#header .nav .link { color: #333; }  /* 特異性 0,1,1,1 */

/* 後來想覆蓋某頁面導航顏色,需更高特異性 */
.page-about #header .nav .link { color: #007bff; }  /* 0,1,1,1 → 後寫者勝,但脆弱 */
/* 或被迫用 !important */
.link--highlight { color: #007bff !important; }  /* 污染代碼庫 */

現代最佳實踐:棄用 ID 做樣式,改用 Class

/* ✅ 推薦:低特異性 class,易覆蓋、易複用、語意化 */
.site-header { ... }
.main-content { ... }
.site-footer { ... }

.nav { ... }
.nav__link { ... }
.nav__link--active { ... }  /* BEM Modifier */

/* 頁面級變體:在 body/page-wrapper 加類別 */

.page-about .nav__link { color: var(--color-primary); }  /* 特異性 0,0,2,0 易覆蓋 */

ID 保留場景

  1. JS 掛鉤:document.getElementById()、label[for="id"]、aria-labelledby
  2. 頁面內錨點:<a href="#section1"> 對應 <section id="section1">
  3. 表單關聯:<label for="email"> + <input id="email">
  4. SVG 符號引用:<use href="#icon-home">

遷移策略

  1. 新代碼嚴禁 ID 做樣式
  2. 舊代碼重構時逐步替換為 Class
  3. Stylelint 規則禁止 ID 選擇器:"selector-max-id": 0
  4. 保留 JS/錨點/無障礙所需的 ID
copyright © 萬盛學電腦網 all rights reserved