在CSS中,类选择器(Class Selector)用于选择具有特定类名的HTML元素。类选择器以点号(.)开头,后面跟着类名。
.class-name {
/* 样式规则 */
}
选择所有具有指定类名的元素:
.button {
background-color: blue;
color: white;
}
限制只选择特定类型的元素:
div.highlight {
border: 2px solid yellow;
}
选择同时具有多个类的元素:
.btn.btn-primary {
background-color: darkblue;
}
选择特定类名的后代元素:
.container .item {
margin: 10px;
}
选择特定类名的直接子元素:
.menu > .menu-item {
padding: 5px;
}
选择紧接在另一个元素后的特定类名元素:
.heading + .content {
margin-top: 20px;
}
选择所有在另一个元素后的特定类名元素:
.section ~ .subsection {
color: gray;
}
使用属性选择器选择类名:
[class~="warning"] {
color: red;
}
原因:
解决方案:
!important
(谨慎使用)原因: 类选择器过于通用
解决方案:
原因: JavaScript动态添加类名时,CSS规则可能已解析完成
解决方案:
:not()
排除不需要的元素<!DOCTYPE html>
<html>
<head>
<style>
/* 基本类选择器 */
.highlight {
background-color: yellow;
}
/* 结合元素类型的类选择器 */
p.note {
font-style: italic;
color: #666;
}
/* 多类选择器 */
.btn.danger {
background-color: red;
}
/* 后代选择器 */
.card .title {
font-size: 1.5em;
}
/* 子元素选择器 */
.menu > .item {
padding: 8px;
}
</style>
</head>
<body>
<p class="highlight">这是一个高亮段落</p>
<div class="highlight">这是一个高亮div</div>
<p class="note">这是一个注释段落</p>
<div class="note">这个div不会应用note样式</div>
<button class="btn">普通按钮</button>
<button class="btn danger">危险按钮</button>
<div class="card">
<h2 class="title">卡片标题</h2>
<div class="content">卡片内容</div>
</div>
<ul class="menu">
<li class="item">菜单项1</li>
<li class="item">菜单项2</li>
</ul>
</body>
</html>
通过合理使用类选择器,可以创建模块化、可维护的CSS代码结构。
没有搜到相关的文章