ID 選擇器
CSS ID 選擇器根據元素的 id 屬性值來匹配元素。為了使元素被選中,它的 id 屬性必須與選擇器中給出的值完全匹配。
css
/* The element with id="demo" */
#demo {
border: red 2px solid;
}
語法
css
#id_value {
/* … */
}
請注意,在語法上(但在特異性上不同),這等同於以下屬性選擇器
css
[id="id_value"] {
/* … */
}
id_value 值必須是有效的 CSS 識別符號。不是有效 CSS 識別符號的 HTML id 屬性在使用 ID 選擇器之前必須進行轉義。
示例
有效的 ID 選擇器
HTML
html
<p id="blue">This paragraph has a blue background.</p>
<p>This is just a regular paragraph.</p>
html
<!-- The next two paragraphs have id attributes
that contain characters which must be escaped in CSS -->
<p id="item?one">This paragraph has a pink background.</p>
<p id="123item">This paragraph has a yellow background.</p>
CSS
css
#blue {
background-color: skyblue;
}
css
/* In the next two rules, the id attributes must be escaped */
#item\?one {
background-color: pink;
}
#\00003123item {
background-color: yellow;
}
結果
無效的 ID 選擇器
以下規則中的 ID 選擇器不是有效的 CSS 識別符號,將被忽略。
css
#item?one {
background-color: green;
}
#123item {
background-color: green;
}
規範
| 規範 |
|---|
| 選擇器 Level 4 # ID-選擇器 |
瀏覽器相容性
載入中…