CSS class selector matches elements based on the contents of their class 属性。

/* All elements with class="spacious" */
.spacious {
  margin: 2em;
}
/* All <li> elements with class="spacious" */
li.spacious {
  margin: 2em;
}
/* All <li> elements with a class list that includes both "spacious" and "elegant" */
/* For example, class="elegant retro spacious" */
li.spacious.elegant {
  margin: 2em;
}
					

句法

.class_name { style properties }
					

Note that this is equivalent to the following attribute selector :

[class~=class_name] { style properties }
					

范例

CSS

.red {
  color: #f33;
}
.yellow-bg {
  background: #ffa;
}
.fancy {
  font-weight: bold;
  text-shadow: 4px 4px 3px #77f;
}
					

HTML

<p class="red">This paragraph has red text.</p>
<p class="red yellow-bg">This paragraph has red text and a yellow background.</p>
<p class="red fancy">This paragraph has red text and "fancy" styling.</p>
<p>This is just a regular paragraph.</p>
					

结果

规范

规范 状态 注释
Selectors Level 4
The definition of 'class selectors' in that specification.
工作草案 No changes
Selectors Level 3
The definition of 'class selectors' in that specification.
推荐
CSS Level 2 (Revision 1)
The definition of 'child selectors' in that specification.
推荐
CSS Level 1
The definition of 'child selectors' in that specification.
推荐 初始定义

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
Class selector ( .className ) Chrome 完整支持 1 Edge 完整支持 12 Firefox 完整支持 1 IE 完整支持 3 Opera 完整支持 3.5 Safari 完整支持 1 WebView Android 完整支持 ≤37 Chrome Android 完整支持 18 Firefox Android 完整支持 4 Opera Android 完整支持 10.1 Safari iOS 完整支持 1 Samsung Internet Android 完整支持 1.0

图例

完整支持

完整支持

元数据

  • 最后修改: