类选择器
CSS 类选择器根据元素的 class 属性的内容来匹配元素。
css
/* 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;
}
语法
css
.class_name {
/* … */
}
请注意,这等同于以下属性选择器
css
[class~="class_name"] {
/* … */
}
class_name 值必须是有效的 CSS 标识符。并非有效 CSS 标识符的 HTML class 属性在使用类选择器之前必须进行转义。
示例
有效类选择器
HTML
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>
html
<!-- The next two paragraphs have class attributes
that contain characters which must be escaped in CSS -->
<p class="item?one">This paragraph has a pink background.</p>
<p class="123item">This paragraph has a yellow background.</p>
CSS
css
.red {
color: #ff3333;
}
.yellow-bg {
background: #ffffaa;
}
.fancy {
font-weight: bold;
text-shadow: 4px 4px 3px #7777ff;
}
css
/* In the next two rules, the class attributes must be escaped */
.item\?one {
background-color: pink;
}
.\00003123item {
background-color: yellow;
}
结果
无效类选择器
以下规则中的类选择器不是有效的 CSS 标识符,将被忽略。
css
.item?one {
background-color: green;
}
.123item {
background-color: green;
}
规范
| 规范 |
|---|
| 选择器 Level 4 # class-html |
浏览器兼容性
加载中…