剛接觸 Web 標準的人,常會把 id 與 class 當成可以隨意替換的兩種標記。實際上它們在唯一性、優先級與腳本操作三個層面上,有明確而關鍵的差異。
第一個例子,同一個元素同時帶有 id 與 class,樣式剛好衝突:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="zh" lang="zh">
<head profile="https://www.w3.org/2000/08/w3c-synd/#">
<meta http-equiv="content-language" content="zh-cn" />
<meta http-equiv="content-type" content="text/html;charset=gb2312" />
<title>blueidea</title>
<style type="text/CSS">
#aa { color:red }
.aa { color:blue }
</style>
</head>
<body>
<div id="aa" class="aa">aaaaaaaaa</div>
</body>
</html>
第二個例子,一個元素掛上多個 class:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="zh" lang="zh">
<head profile="https://www.w3.org/2000/08/w3c-synd/#">
<meta http-equiv="content-language" content="zh-cn" />
<meta http-equiv="content-type" content="text/html;charset=gb2312" />
<title>blueidea</title>
<style type="text/CSS">
.a { color:orange }
.b { background:#eee }
.c { border:1px solid red }
</style>
</head>
<body>
<div class="a b c">aaaaaaaa</div>
</body>
</html>
標準明確要求 id 在一份文件中必須唯一。像 div id="aa" 這樣的寫法,同一頁面出現第二次就是不合法的文件。而 class 定義的是「類別」,同一個 class 可以被任意多個元素引用;需要重複套用的樣式,本來就該寫成 class。
反過來,一個元素可以同時掛多個 class,彼此以空格隔開(如範例二的 class="a b c"),這是 id 做不到的。實務上常見的組合是「一個 id 定位結構,數個 class 描述狀態」,例如 <ul id="nav" class="menu active">。
第一個範例裡,#aa 與 .aa 同時命中同一個元素,最終文字會是紅色。原因在於選擇器的權重(specificity)計算:id 的權重高於 class,因此 id 的宣告勝出。
這也是實務上的重要提醒——不要為了「先寫一個 class,之後再覆蓋」而隨手用 id,否則後續想用 class 微調會發現怎麼改都沒反應,只能回頭用 !important 硬掰,讓樣式表越來越難維護。
若需要用 JavaScript 對某個特定元素做操作,給它一個 id 是最省事的做法。透過 id 可以直接取得該元素,不必遍歷整份文件去比對標籤名稱與屬性。
以現代寫法為例:
// 原生 API:id 是查詢最快的入口
var box = document.getElementById('aa');
// class 對應「一群」元素,回傳集合
var items = document.querySelectorAll('.aa');
差別一目了然:id 回答「是哪一個」,class 回答「有哪些」。把這兩個問題分清楚,命名與樣式結構自然就不會糾纏。