0
点赞
收藏
分享

微信扫一扫

CSS中常用的四种选择器


Css中常用的四种选择器

1、类选择器(class选择器)

      基本使用:

类选择器{

: 属性值;

            ...

      }

      案例:


/*类选择器*/
.s1{
background-color: pink;
font-weight: bold;
font-size: 16px;
color: black;
}

2、id选择器

      基本使用:

选择器{

: 属性值;

             ...

      }

      案例:

/*id选择器的使用*/
#id1{
background-color: silver;
font-size: 40px;
}

3、html元素选择器

html元素{

: 属性值;

             ...

      }

      案例:

a:link{
color: black;
text-decoration: none;
font-size: 24px;
}
a:visited{
color: red;
}
a:hover{
color: green;
text-decoration: underline;
font-size: 40px;
}

/*对同一种html元素分类*/
p.cls1{
color:blue;
font-size:30px;
}
p.cls2{
color:red;
font-size:20px;
}

      a 元素的效果为:

(1)默认样式是黑色,24px,没有下划线;

(2)当鼠标移动到超链接时,自动出现下划线;

(3)点击后,超链接变成红色。


      p 元素的选择器在html中的使用,如:

<p class="cls1">hello,world!hello,world!hello,world!</p>
<p class="cls2">hello,html!hello,html!hello,html!</p>

4、通配符选择器

该选择器可以用到所有的html元素,但是其优先权最低

      *{

: 属性值;

            ...

      }

      案例:

/*通配符选择器*/
*{
/*margin-top:0px;
margin-left:0px;*/
/*margin: 10px 30px 40px 1px;*/
/*margin 可以写一个值,(上右下左(顺时针))如果是两个值(上下,左右)
如果是是三个值(上,左右,下)*/
margin:0px;
padding:0px;
}


四个选择器的优先权如下:

Id选择器 > class选择器 > html选择器 > 通配符选择器

选择器的细节问题!!!

1、父子选择器的使用

/*父子选择器*/
/*对id选择器为#id1下的span元素定义样式*/
#id1 span{
color: red;
font-style:italic;
}
/*对id选择器为#id1下的span元素下的span元素定义样式*/
#id1 span span{
color:green;
}
#id1 span span a{
color:blue;
}

通过上面总结:

(1)父子选择器可以有多级(但是在实际开发中,建议不要超过三层);

(2)父子选择器有严格的层级关系;

(3)父子选择器不局限于什么类型选择器,比如

#id span span

s1 #id span

div #id s2


2、一个元素可以同时有id选择器和类选择器(但是id选择器不可以有多个)

案例:


<span class="s1" id="tid">TestId</span>


3、一个元素最多有一个id选择器,但是可以有多个类选择器。

使用方法如下:

<元素 class=”类选择器1 类选择器2”>内容</元素>

案例:


/*类选择器1*/
.s1{
background-color: pink;
font-weight: bold;
font-size: 16px;
color: black;
}
/*再配置一个类选择器2*/
.cls1{
font-style:italic;
text-decoration:underline;
}

(注:这里需要注意的是,当同时使用多个类选择器且类选择器中的样式发生冲突时,以CSS文件中最尾的类选择器的样式为准,不依赖于html文件中的类选择器的放置顺序。)


4、我们可以把某个CSS文件中的选择器共有的部分,独立出来写成一份。比如:

/*招生广告*/
.ad_stu{
width:136px;
height:196px;
background-color:#FC7E8C;
margin:5px 0 0 6px;
float:left;
}

/*广告2*/
.ad_2{
background:#7CF574;
height:196px;
width:457px;
float:left;
margin:5px 0 0 6px;
}

/*房地产广告*/
.ad_house{
background:#7CF574;
height:196px;
width:152px;
float:left;
margin:5px 0 0 6px;
}

//上面的CSS可以写成

/*招生广告*/
.ad_stu{
width:136px;
background-color:#FC7E8C;
}

/*广告2*/
.ad_2{
background:#7CF574;
height:196px;
width:457px;
}

/*房地产广告*/
.ad_house{
background:#7CF574;
height:196px;
width:152px;
}

.ad_stu, .ad_2, .ad_house{
height:196px;
margin:5px 0 0 6px;
float:left;
}

5、CSS文件本身也会被浏览器从服务器下载到本地,才能显示效果。


举报

相关推荐

0 条评论