id 選擇器以井號 # 開頭,對應 HTML 元素的 id 屬性。同一頁面中 ID 必須唯一,不可重複。
/ * HTML * /
主要內容區塊
/ * CSS * /
#content {
font-size: 14px;
line-height: 1.5;
}
#header、#footer、#sidebar、#main、#wrapper#login-form、#search-box、#user-profile#section-about、#section-contact!important。document.getElementById() 效能最佳。<a href="#section"> 可跳轉至對應 ID 元素。| 場景 | 建議 |
|---|---|
| 版面大區塊(唯一) | ID |
| 重複出現的 UI 元件 | Class |
| JavaScript 需快速選取 | ID |
| 樣式需複用/組合 | Class |
| 頁面內錨點跳轉 | ID |
| 狀態修飾(active, disabled) | Class |
#box、#div1)→ 語意不清,易衝突。ID 選擇器專為「唯一標識」設計,CSS 中宜少用、精用(僅針對版面級唯一區塊或極少數高優先級覆寫),樣式複用請一律改用 Class。