nth-child与nth-of-type

  nth-of-type这个CSS3伪类还从来没有用过,今天好好研究一番,发现还是有用的。现在下面的Demo

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8"> 
    <title>test</title> 
        <style>
            .test1 p:nth-of-type(1) {
                color: blue;
            }

            .test2 p:nth-child(1), .test3 p:nth-child(1) {
                color: blue;
            }

        </style>
    </head>

    <body>
        <div class="test1">
            <a>This is some .</a>
            <p>This is some text.</p>
            <p>This is some text.</p>
        </div>

        <br>

        <div class="test2">
            <a>This is some .</a>
            <p>This is some text.</p>
            <p>This is some text.</p>
        </div>

        <br>

        <div class="test3">
            <p>This is some text.</p>
            <p>This is some text.</p>
        </div>


    </body>
</html>

显示结果如下

 

可见,p:nth-of-type(1)是取父元素下的p这种类型的第一个,p前面可能会有其它类型的元素;而p:nth-child(1)是父元素的第一个元素,且该元素必须是p。可以参考这篇文章,CSS3 选择器——伪类选择器 但这篇文章有些方向错误,认为nth-of-type在工作中没用。其实在某些情况下还是十分有用的。

posted @ 2019-06-17 18:45  姜瑞涛  阅读(168)  评论(0编辑  收藏  举报