Skip to main content

选择器

:nth-child() 选择器

实例

指定每个 p 元素匹配的父元素中第 2 个子元素的背景色:

p:nth-child(2)
{
background:#ff0000;
}

定义和用法

:nth-child(n) 选择器匹配父元素中的第 n 个子元素,元素类型没有限制。

n 可以是一个数字,一个关键字,或者一个公式。

提示: 请参阅选择器。该选择器匹配同类型中的第 n 个同级兄弟元素。

链接

:nth-child() 选择器

:first-child 选择器

实例

匹配 <p> 的父元素的第一个<p>元素:

p:first-child(2)
{
background-color:yellow;
}

定义和用法

:first-child 选择器匹配其父元素中的第一个子元素。

:last-child 选择器

实例

指定父元素中最后一个p元素的背景色:

p:last-child(2)
{
background:#ff0000;
}

定义和用法

:last-child 选择器匹配其父元素中的最后一个子元素。

:nth-last-of-type() 选择器

实例

指定每个p元素匹配同类型中的倒数第2个同级兄弟元素背景色:

p:nth-last-of-type(2)
{
background:#ff0000;
}

定义和用法

:nth-last-of-type(n)选择器匹配同类型中的倒数第n个同级兄弟元素。

n 可以是一个数字,一个关键字,或者一个公式。

提示:请参阅::nth-last-child()选择器。该选择器匹配父元素中的倒数第n个结构子元素

:first-of-type 选择器

实例

选择的 p 元素是其父元素的第一个 p 元素:

p:first-of-type
{
background:#ff0000;
}

定义和用法

:first-of-type 选择器匹配元素其父级是特定类型的第一个子元素。

提示: 和 :nth-of-type(1) 是一个意思。

:last-of-type 选择器

实例 指定其父级的最后一个p元素的背景色:

p:last-of-type
{
background:#ff0000;
}

定义和用法

:last-of-type选择器匹配元素其父级是特定类型的最后一个子元素。

提示: 和:nth-last-of-type(1)是一个意思。