css样式的六种选择器
css常⽤的选择器有:
1.标签选择器:
标签选择器,这种选择器影响范围⼤,建议尽量应⽤在层级选择器中。
如:
*{margin:0;padding:0}  /* 影响所有的标签 */
div{color:red} /* 影响所有的div标签 */
<div>......</div>  <!-- 对应以上两条样式 -->
<div class=”box”>......</div>  <!-- 对应以上两条样式 -->
2.id选择器:
通过id名来选择元素,元素的id名称不能重复,所以⼀个样式设置项只能对应于页⾯上⼀个元素,不能复⽤,id名⼀般给程序使⽤,所以不推荐使⽤id作为选择器。
id是所有标签的属性,所有标签都有id属性,写代码时id的值是不允许重复的
如:
#box{color:red}
<div id=”box”>......</div> <!-- 对应以上⼀条样式,其它元素不允许应⽤此样式 -->
3.类选择器:(常⽤)
通过类名来选择元素,⼀个类可应⽤于多个元素,⼀个元素上也可以使⽤多个类,应⽤灵活,可复⽤,是css中应⽤最多的⼀种选择器。如:
.red{color:red}
.big{font-size:20px}
.mt10{margin-top:10px}
<div class=”red”>......</div>
4.层级选择器:
主要应⽤在选择⽗元素下的⼦元素,或者⼦元素下⾯的⼦元素,可与标签元素结合使⽤,减少命名,同时也可以通过层级,防⽌命名冲突。如:
.box span{color:red}
.box .red{color:pink}
.red{color:red}
<div class=”box”>
<span>......</span>
<a href=”#” class=”red”>......</a>
</div>
<h3 class=”red”>......</h3>
层级选择器最好不要超过四层,否则会影响性能。
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>层级选择器</title>
<style type="text/css">
.box{
font-size:20px;
line-height:40px;
text-indent:40px;
}
.
box span{
color:red;
font-weight:bold;
}
.box em{
font-style:normal;
text-decoration:underline;
font-weight:bold;
color:pink;
}
.box .span02{
color:blue;
}
</style>
</head>
<body>
<div class="box">
<!-- 层级选择器最好不要超过四层 -->
层级选择器主要应⽤于选择⽗元素下的<span>⼦元素</span>,或者⼦元素下⾯的<span class="span02">⼦元素</span>,可与标签元素结合使⽤,减少命名,同时也可以通过层级,<em>防⽌命名冲突</em>。
</div>
<div class="box2">
层级选择器主要应⽤于选择⽗元素下的<span>⼦元素</span>,或者⼦元素下⾯的⼦元素,
可与标签元素结合使⽤,减少命名,同时也可以通过层级,防⽌命名冲突。
</div>
</body>
</html>
5.组选择器:
多个选择器,如果有同样的样式设置,可以使⽤组选择器。
(组选择器之间⽤逗号分隔;层级选择器之间⽤空格分隔)
如:
.box1,.box2,.box3{width:100px;height:100px}
.box1{background:red}
.
box2{background:pink}
.box2{background:gold}
6.伪类及伪元素选择器:
常⽤的伪类选择器有hover,表⽰⿏标悬浮在元素上时的状态,伪元素选择器有before和after,它们可以通过样式在元素中插⼊内容。⼀般⽤在链接的响应
如:
.box1:hover{color:red}
.box2:before{content:’⾏⾸⽂字’;}
.box3:after{content:’⾏尾⽂字’;}
<div class=”box1”>......</div>
<div class=”box2”>......</div>
<div class=”box3”>......</div>
<div class=”box1”>......</div>
<div class=”box2”>......</div>
<div class=”box3”>......</div>
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>伪类和伪元素选择器</title>
<style type="text/css">
.link{
font-size:30px;
text-decoration:none;
color:green;
}
.link:hover{    /* 伪类选择器⿏标悬浮时 */
color:gold;
font-weight:bold;
font-style:italic;
}
.box01,.box02{
font-size:20px;
}
.box01:before{  /* 伪元素选择器在伪元素前加⼀些内容,此添加的内容页⾯上是选不中的 */
/*content:"前⾯的⽂字";*/
content:".";  /* 伪元素前加上⼀个. */
color:red;
}
.box02:after{
content:">>End";
color:gold;
css选择器分为哪几类}
</style>
</head>
<body>
<a href="www.baidu" class="link">百度⼀下</a> <div class="box01">这是第⼀个div</div>
<div class="box02">这是第⼆个div</div>
</body>
</html>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。