ID 选择器

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

CSS ID 选择器会根据该元素的 id 属性中的内容匹配元素。为了使该元素被选中,它的 id 属性必须与选择器中给出的值完全匹配。

css
/* id 为 "demo" 的元素会被选中 */
#demo {
  border: red 2px solid;
}

语法

css
#id 属性值 { 样式声明 }

它与下面的属性选择器语句语法上等价(但优先级并不等价):

css
[id=id 属性值] { 样式声明 }

示例

CSS

css
#identified {
  background-color: skyblue;
}

HTML

html
<div id="identified">这个 div 有一个特别的 ID 属性!</div>
<div>这只是一个普通的 div。</div>

结果

规范

Specification
Selectors Level 4
# id-selectors

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
ID selector (#idName)

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见