代码改变世界

说说九个CSS3结构性伪类选择器

2011-09-23 22:58  狼人:-)  阅读(130)  评论(0)    收藏  举报

我们在52CSS前面的文章中,陆续为大家讲了多种CSS选择器。今天说说九个CSS3结构性伪类选择器。

一、X:nth-child(n)

div css xhtml xml Example Source Code Example Source Code [www.52css.com]

li:nth-child(3) {

color: red;

}

接下来的几个伪类选择器使用上非常类似,功能也比较接近。

:nth-child(n),用于匹配索引值为n的子元素。索引值从1开始。

X:nth-child()用法实际上有三种变化,demo的用法是最简单的,X:nth-child()更强大的用处在于奇偶匹配,明河不展开讲,有兴趣的请看《Understanding :nth-child Pseudo-class Expressions》,《CSS3 :nth-child()伪类选择器》

二、X:nth-last-child(n)

div css xhtml xml Example Source Code Example Source Code [www.52css.com]

li:nth-last-child(2) {

color: red;

}

:nth-child(n),是从第一个开始算索引,而X:nth-last-child(n)是从最后一个开始算索引。

三、X:nth-of-type(n)

div css xhtml xml Example Source Code Example Source Code [www.52css.com]

ul:nth-of-type(3) {

border: 1px solid black;

}

nth-of-type与nth-child的效果是惊人的相似,想要更多的了解nth-of-type请看《Alternative for :nth-of-type() and :nth-child()》,:nth-of-type(N)

四、X:nth-last-of-type(n)

div css xhtml xml Example Source Code Example Source Code [www.52css.com]

ul:nth-last-of-type(3) {

border: 1px solid black;

}

:nth-last-child效果相似。

五、X:first-child

div css xhtml xml Example Source Code Example Source Code [www.52css.com]

ul li:first-child {

border-top: none;

}

匹配子集的第一个元素。IE7就可以支持了,这个伪类还是非常有用的。

六、X:last-child

div css xhtml xml Example Source Code Example Source Code [www.52css.com]

ul > li:last-child {

color: green;

}

与:first-child效果相反

留意IE8支持:first-child,但不支持:last-child。

七、X:only-child

div css xhtml xml Example Source Code Example Source Code [www.52css.com]

div p:only-child {

color: red;

}

这个伪类一般用的比较少,比如上述代码匹配的是div下的有且仅有一个的p,也就是说,如果div内有多个p,将不匹配。

八、X:only-of-type

div css xhtml xml Example Source Code Example Source Code [www.52css.com]

li:only-of-type {

font-weight: bold;

}

与:only-child类似。

九、X:first-of-type

div css xhtml xml Example Source Code Example Source Code [www.52css.com]

ul:first-of-type{

font-weight: bold;

}

等价于:nth-of-type(1),匹配集合元素中的第一个元素。

本文转自:http://www.52css.com/default.asp?id=1188