CSS选择器

最详细的CSS选择器

在如今的网页前端设计中想要给网页中的某些元素添加样式,这时我们就会联想到选择器这个概念,在早期的网页开发中最为常用的选择器为 ‘class选择器’,和’ID‘选择器,但如今随着CSS3技术的普及,人们对选择器的概念有了一个新的认识,今天就跟随着思鹏的步伐一起来感受一下选择器的独特魅力。

calss 和ID选择器

该技术为早期网页开发中常用的技术,其使用方法是为DOM元素赋予class名称和ID名称,然后在style块中选择该元素达到锁定元素的效果,例如

        class选择器                     

<div class="box"></div>   DOM元素    

   .box{background:red;}        样式 -- class选择器使用 . 点名称的方式选择该元素  


  ID选择器

<div id="box"></div>DOM元素

 #box{background:blue;}  样式 id选择器使用 #名称的方式选择该元素


注意:在同一页面中ID名称不可重复,class名称可重复,即保证ID唯一。


属性选择器:


例1:

a[class^=box]{ /*寻找页面中类名以box开头的class名称*/

  color:red;

}


a[class$=box]{/寻找页面中类名以box结尾的class名称**/

color:red;

}


.box [class*="span"]{/*寻找.box下的所有span元素*/
}


例2:

 a[href$=zip]{ /*选择页面中所有A连接的href值指向一个zip文件的元素*/

color:red;

}

例3:

a[title*=sp]{ /*选择页面中所有A连接的title值为 sp 的元素*/

color:red;

}

伪类选择器:

该选择器为CSS3中的特有的属性,即不支持css3的浏览器使用该属性是没有任何效果的。

1.

nth-child(num){}

例如

.box ul li:nth-child(1){background:red;}

给class名称为box下的ul下的第一个li添加样式

以此类推

.box ul li:nth-child(2){background:red;}

.box ul li:nth-child(3){background:red;}

2.

frist-child{}

例如

.box ul li:frist-child{background:red;}

给class名称为box下的ul下的第一个li添加样式

3.

last-child{}

例如:.box ul li:last-child{background:red;}


给class名称为box下的ul下的最后一个li添加样式

4.

nth-last-child(num){}

例如:.box ul li:nth-last-child(2){background:red;}

给class名称为box下的ul下的倒数第二个li添加样式

属性不同于nth-child(num){}的是

nth-child(num)从指定元素的头部开始计算

nth-last-child(num)从指定元素的尾部开始计算

5.of-type

 /*
    nth-of-type:查找某一特定类型的所有N个元素
*/
.box1 span:nth-of-type(2){background:red;}
.box1 span:nth-of-type(1){background:green;}
.box1 span:nth-of-type(3){background:blue;}
.box1 p:nth-of-type(1){background:red;}

/*
    first-of-type:查找某一特定类型的第一个元素
*/
.box span:first-of-type{color:red;}/*给.box元素下的第一个span元素赋予样式*/

 /*
    last-of-type:查找某一特定类型的最后一个元素
*/
.box span:last-of-type{color:#00ff66;}/*给.box 元素下的最后一个span元素赋予样式*/


以上就是在css中常用的选择器,由于思鹏也是一个前端方面的菜鸟,如有写的不对的地方还请大家多多包涵。

验证码: 看不清楚?