ITeye博客

CSS3 新增伪类选择器

小丑鱼0703 · 2015-03-27 11:09 · CSS3 · Web前端 · Markdown

伪类选择器

:nth-child(n)选择器 用来定位某个父元素的一个或多个特定的子元素。其中“n”是其参数,而且可以是整数值(1,2,3,4),也可以是表达式(2n+1、-n+5)和关键词(odd、even),但参数n的起始值始终是1,而不是0!表达式的值为0或小于0的时候,不选择任何匹配的元素。

:nth-last-child(n)选择器 和“:nth-child(n)”选择器非常相似,只是从某父元素的最后一个子元素开始计算来选择特定的元素。

:first-of-type选择器 类似于“:first-child”选择器,不同之处就是指定了元素的类型,其主要用来定位一个父元素下的某个类型的第一个子元素。

:last-of-type选择器 和“:first-of-type”选择器功能一样,不同的是选择父元素下的某个类型的最后一个子元素。

nth-of-type(n)选择器 只计算父元素中指定的某种类型的子元素。当某个元素中的子元素不单单是同一种类型的子元素时,使用“:nth-of-type(n)”选择器来定位于父元素中某种类型的子元素是非常方便和有用的。 “n”参数可以是具体的整数,也可以是表达式,还可以是关键词。

:nth-last-of-type(n)选择器 和“:nth-of-type(n)”选择器一样,选择父元素中指定的某种子元素类型,但它的起始方向是从最后一个子元素开始。

:only-child选择器 匹配元素的父元素中有且只有唯一的一个子元素。

:only-of-type选择器 用来选择一个元素是它的父元素的唯一一个相同类型的子元素。

  【实例1:】将容器“div.wrapper”中偶数段落和奇数Div背景设置为橙色,将第一个div背景设置为绿色,最后一个p背景设置为蓝色。

.wrapper > div:nth-of-type(2n+1),
.wrapper > p:nth-of-type(2n){
  background: orange;
}
/*或者*/
.wrapper > div:nth-of-type(2n-1),
.wrapper > p:nth-of-type(2n){
  background: orange;
}
/*或者*/
.wrapper > div:nth-of-type(odd),
.wrapper > p:nth-of-type(even){
  background: orange;
}
.wrapper > div:first-of-type{
  background: green;
}
.wrapper > p:last-of-type{
  background: blue;
}

   ![](http://dl2.iteye.com/upload/attachment/0107/0063/331b76bb-c4b9-3a0b-920c-b233b5d24f21.jpg)

    【实例2:】将仅有一个P元素类型的背景修改为橙色,有且只有一个元素背景改为蓝色
.wrapper {
  border: 1px solid #ccc;
  padding: 5px;
  width: 150px;
}
.wrapper p:only-of-type{
  background: orange;
}
.wrapper p:only-child{
  background: blue;
}
   ![](http://dl2.iteye.com/upload/attachment/0107/0099/4f9d6eca-db34-3ba1-a373-7f393bc05212.jpg)

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。