类名选择器

类名选择器选择具有目标类名的所有元素。例如,类名 .warning 将选择以下 <div> 元素:

<div class="warning">
    <p>This would be some warning copy.</p>
</div>

你还可以更具体地将类名组合到目标元素。让我们以上面的例子为基础,展示一个更复杂的类选择。

CSS

.important {
    color: orange;
}
.warning {
    color: blue;
}
.warning.important {
    color: red;
}

HTML

<div class="warning">
    <p>This would be some warning copy.</p>
</div>

<div class="important warning">
    <p class="important">This is some really important warning copy.</p>
</div>

在这个例子中,与 .warning 类的所有元素都会有一个蓝色的文本颜色,随用随 .important 类元素有一个橙色的文本颜色,并有所有的元素.important.warning 类名称将有红色文字的颜色。

请注意,在 CSS 中,.warning.important 声明在两个类名之间没有任何空格。这意味着它只会在 class 属性中找到包含类名 warningimportant 的元素。这些类名可以在元素上以任何顺序排列。

如果 CSS 声明中的两个类之间包含空格,则只会选择具有 .warning 类名的父元素和具有 .important 类名的子元素的元素。