类选择器
该 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;
}
语法
示例
有效的类选择器
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: #f33;
}
.yellow-bg {
background: #ffa;
}
.fancy {
font-weight: bold;
text-shadow: 4px 4px 3px #77f;
}
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;
}
规范
规范 |
---|
选择器级别 4 # class-html |
浏览器兼容性
BCD 表格仅在浏览器中加载