使用 class 选择器可以为 HTML 中的特定元素应用样式。class 选择器以 "." 符号开头,后面跟上要应用样式的类名。例如,如果要将所有 class 为 "box" 的元素的背景颜色设置为红色,可以使用以下 CSS 代码:
.box {
background-color: red;
}
在 HTML 中,可以将 class 属性添加到任何元素中,例如:
<div class="box">这是一个红色的盒子</div>
<p class="box">这是一个红色的段落</p>
注意,class 名称必须唯一,不同元素之间的 class 名称可以重复。要选择多个 class,可以将它们用空格分隔,例如:
.box1 {
background-color: red;
}
.box2 {
background-color: blue;
}
.box3 {
background-color: green;
}
.box1, .box2, .box3 {
border: 1px solid black;
}
这将选择所有 class 名称为 "box1"、"box2" 或 "box3" 的元素,并将它们的边框设置为 1px 的黑色实线。
总之,使用 class 选择器可以帮助我们更好地控制和设计网页中的元素。