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;
} </style> </head>
<body>
<a href="https://www.baidu.com" class="link">百度一下</a> <div class="box01">这是第一个div</div>
<div class="box02">这是第二个div</div> </body>
</html>
上一篇:关于Python, ftplib模块中的cwd()进入含中文目录失败的问题


下一篇:VS2012以后版本MFC程序发布记录,支持XP