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-选择器 |
浏览器兼容性
加载中…