大网数据广告活动
Web 标准与前端开发

Class selectors

· 52CE 我爱测

The CSS **class selector** matches elements based on the contents of their `class` attribute.

The CSS class selector matches elements based on the contents of their class attribute.

/* 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;
}

Syntax

.class_name {
  /* … */
}

Note that this is equivalent to the following attribute selector:

[class~="class_name"] {
  /* … */
}

The class_name value must be a valid CSS identifier. HTML class attributes which are not valid CSS identifiers must be escaped before they can be used in class selectors.

Examples

Valid class selectors

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>


<p class="item?one">This paragraph has a pink background.</p>
<p class="123item">This paragraph has a yellow background.</p>

CSS

.red {
  color: #ff3333;
}

.yellow-bg {
  background: #ffffaa;
}

.fancy {
  font-weight: bold;
  text-shadow: 4px 4px 3px #7777ff;
}
/* In the next two rules, the class attributes must be escaped */

.item\?one {
  background-color: pink;
}

.\00003123item {
  background-color: yellow;
}

Result

Examples

Invalid class selectors

The class selectors in the following rules are not valid CSS identifiers, and will be ignored.

.item?one {
  background-color: green;
}

.123item {
  background-color: green;
}

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。