---
title: "CSS3 新增伪类选择器"
author: "小丑鱼0703"
date: "2015-03-27T11:09:27Z"
tags: []
categories: ["Web前端"]
slug: "css3"
draft: false
lastmod: "2015-03-26T17:41:32Z"
id: 2195860
url: "https://wangjingyi.iteye.com/blog/2195860"
---

伪类选择器

**:nth-child(n)选择器**
    用来定位某个父元素的一个或多个特定的子元素。其中“n”是其参数，而且可以是整数值(1,2,3,4)，也可以是表达式(2n+1、-n+5)和关键词(odd、even)，但参数n的<span style="color:red">起始值始终是1</span>，而不是0!表达式的值为0或小于0的时候，不选择任何匹配的元素。

**:nth-last-child(n)选择器**
    和“:nth-child(n)”选择器非常相似，只是从某父元素的最后一个子元素开始计算来选择特定的元素。

**:first-of-type选择器**
    类似于“:first-child”选择器，不同之处就是指定了元素的类型,其主要用来定位一个**父元素**下的<span style="color:blue">某个类型的第一个子元素</span>。

**:last-of-type选择器**
    和“:first-of-type”选择器功能一样，不同的是选择**父元素**下的<span style="color:blue">某个类型的最后一个子元素</span>。

**nth-of-type(n)选择器**
     只计算父元素中指定的某种类型的子元素。当某个元素中的子元素不单单是同一种类型的子元素时，使用“:nth-of-type(n)”选择器来定位于父元素中某种类型的子元素是非常方便和有用的。
     “n”参数可以是具体的<u>整数</u>，也可以是<u>表达式</u>，还可以是<u>关键词。</u>

**:nth-last-of-type(n)选择器**
     和“:nth-of-type(n)”选择器一样，选择父元素中指定的某种子元素类型，但它的起始方向是从最后一个子元素开始。

**:only-child选择器**
    匹配元素的父元素中<span style="color:blue">有且只有唯一</span>的一个子元素。

**:only-of-type选择器**
    用来选择一个元素是它的父元素的唯一一个相同类型的子元素。

      【实例1：】将容器“div.wrapper”中偶数段落和奇数Div背景设置为橙色，将第一个div背景设置为绿色，最后一个p背景设置为蓝色。

```css

.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元素类型的背景修改为橙色，有且只有一个元素背景改为蓝色

```css
.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)