ID选择器

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

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

语法

#id属性 {样式声明 }

注意它与下面的语句等价 attribute selector:

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

示例

span#identified {
  background-color: DodgerBlue;
}

上面的CSS作用于下面的HTML代码:

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

则会产生下面的效果:

Here's a span with some text.
Here's another.

规范

规范 状态 备注
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 YesSafari Full support 1WebView Android Full support ≤37Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support YesSafari iOS Full support 1Samsung Internet Android Full support 1.0

Legend

Full support  
Full support