CSS基础知识4—CSS选择器
发布时间:2024-10
浏览量:102
本文字数:1811
读完约 7 分钟
1、标签选择器
标签选择器,此种选择器影响范围大,建议尽量应用在层级选择器中。
*{margin:0;padding:0}
div{color:red}<div>....</div> <!-- 对应以上两条样式 --> <div class="box">....</div> <!-- 对应以上两条样式 -->
2、id选择器
通过id名来选择元素,元素的id名称不能重复,所以一个样式设置项只能对应于页面上一个元素,不能复用,id名一般给程序使用,所以不推荐使用id作为选择器。
#div1{
color: rebeccapurple;
}
.green{
color: green;
}
.big{
font-size: 40px;
}<!-- id权重高于类 --> <div id="div1" class="big green">这是第一个div</div>
效果如下:

3、类选择器
通过类名来选择元素,一个类可应用于多个元素,一个元素上也可以使用多个类,应用灵活,可复用,是css中应用最多的一种选择器。
.red{color:red}
.big{font-size:20px}
.mt10{margin-top:10px}<div class="red">....</div> <h1 class="red big mt10">....</h1> <p class="red mt10">....</p>
4、层级选择器
主要应用在选择父元素下的子元素,或者子元素下面的子元素,可与标签元素结合使用,减少命名,同时也可以通过层级,防止命名冲突。
.box{
font-size: 35px;
font-style: normal;
color: black;
text-indent: 70px;
}
.box span{
font-size: 50px;
color: mediumorchid;
font-weight: bold;
text-decoration: underline;
}
.box em{
font-size: 40px;
color: red;
font-style: normal;
font-family: monospace;
}
.box .span02{
color: seagreen;
font-size: 38px;
text-decoration: none;
font-style: italic;
}<div class="box"> <span>层级选择器</span>主要应用在选择父元素下的<span class="span02">子元素</span>,或者子元素下面的子元素,可与标签元素结合使用,<em>减少命名</em>,同时也可以通过层级,<em>防止命名冲突</em>。 </div>
效果如下:

5、组选择器
多个选择器,如果有同样的样式设置,可以使用组选择器。
.zu1,.zu2,.zu3{
margin: 1em;
line-height: 40px;
font-size: 20px;
text-indent: 40px;
}
.zu1{
color: red;
}
.zu2{
color: black;
}
.zu3{
color: rgb(52, 23, 219);
}<!-- 组选择器 --> <div class="zu1">这是组选择器1</div> <div class="zu2">这是组选择器2</div> <div class="zu3">这是组选择器3</div>
效果如下:

6、伪类及伪元素选择器
常用的伪类选择器有hover,表示鼠标悬浮在元素上时的状态,伪元素选择器有before和after,它们可以通过样式在元素中插入内容。
.link{
font-size: 30px;
color: green;
text-decoration: none;
}
<!-- 鼠标悬浮元素上面时 -->
.link:hover{
font-weight: bold;
<!-- 去除下划线 -->
text-decoration:underline;
}
.con1,.con2{
font-size: 30px;
color: rebeccapurple;
}
.con1:before{
content: "伪类前面加文字,展示在页面上的文字无法选中";
color: red;
}
.con2:after{
content: "伪类后面加文字,展示在页面上的文字无法选中";
color: seagreen;
}<!-- 伪类选择器 --> <a href="https://www.baidu.com" class="link">百度一下</a> <div class="con1">伪类选择器1</div> <div class="con2">伪类选择器2</div>
效果如下(鼠标未选中时):

鼠标选中时:
