ID 选择器

在一个HTML文档中,CSS ID 选择器会根据该元素的 ID 属性中的内容匹配元素,元素 ID 属性名必须与选择器中的 ID 属性名完全匹配,此条样式声明才会生效。

/* The element with id="demo" */
#demo {
  border: red 2px solid;
}

语法

#id属性值 {样式声明 }

它与下面的属性选择器语句等价:

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

示例

CSS

span#identified {
  background-color: DodgerBlue;
}

HTML

  <span id="identified">Here's a span with some text.</span>
  <span>Here's another.</span>

结果

规范

规范 状态 备注
Selectors Level 4
ID selectors
Working Draft
Selectors Level 3
ID selectors
Recommendation
CSS Level 2 (Revision 1)
ID selectors
Recommendation
CSS Level 1
ID selectors
Recommendation 初始定义

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
ID selector (#idName)Chrome Full support 1Edge Full support 12Firefox Full support 1IE Full support 3Opera Full support 3.5Safari Full support 1WebView Android Full support ≤37Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android Full support 1.0

Legend

Full support  
Full support