CSS3中:first-child和:first-of-child的区别

html-css07

CSS3中:first-child和:first-of-child的区别,第1张

首先要更正一下,不存在first-of-child的,只有first-of-type

下面就说说

first-child

与first-of-type的区别:

first-child:父元素的第一个子元素且必须符合指定类型

first-of-type:父元素的符合指定类型的第一个子元素

当然,光看文字也是很难理解的,下面看看例子:

第1行

第2行

第3行

这种情况下,不管是p:first-of-type还是p:first-child,

第1行

都会被选中。

而如果是:

第1行

第2行

第3行

第4行

则p:first-of-type的话,

第2行

会被选中;

而p:first-child的话,将没有任何元素被选中!

:first-child /* 匹配第一个元素 */

举例:(parent下的第一个子元素字体变红色)

.parent > :first-child {color:red} <div class="parent">

    <p>子元素1</p>

    <div>子元素2</div>

    <span>子元素3</span>

</div>