Web前端之路

css3中的nth-child(n)和nth-of-type(n

2019-05-22  本文已影响1人  jaimor

这里记录一下看着相似,用法也相似,平时会用但是有可能又用错了的这两个css3选择器。还有几个类似的,如:first-of-type, first-child, last-child等。

解释

注意:下标是从1开始。

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .test .t1 { float: left; margin-right: 50px; }
        .test .t1 { float: left; }

        .test .t1 div:nth-child(4) { color: red; }
        .test .t1 div:nth-of-type(4) { color: green; }

        .test .t2 p:nth-child(7) { color: gray; }
        .test .t2 p:nth-of-type(2) { color: red; }
    </style>
</head>
<body>
    <div class="test">
        <div class="t1">
            This is t1.
            <p>P标签1, child 1</p>
            <div>DIV标签1, child 2</div>
            <div>DIV标签2, child 3</div>
            <p>P标签2, child 4</p>
            <div>DIV标签3, child 5</div>
            <div>DIV标签4, child 6</div>
            <p>P标签3, child 7</p>
        </div>
        <div class="t2">
            This is t2.
            <p>P标签1, child 1</p>
            <div>DIV标签1, child 2</div>
            <div>DIV标签2, child 3</div>
            <p>P标签2, child 4</p>
            <div>DIV标签3, child 5</div>
            <div>DIV标签4, child 6</div>
            <p>P标签3, child 7</p>
        </div>
    </div>
</body>
</html>
测试1结果
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .test .t1 { float: left; margin-right: 50px; }
        .test .t1 { float: left; }

        .test :nth-child(3) { color: red; }
        /*.test *:nth-child(3) { color: red; }*/
        /*.test :nth-of-type(3) { color: green; }*/
        .test *:nth-of-type(3) { color: green; }
    </style>
</head>
<body>
    <div class="test">
        <div class="t1">
            This is t1.
            <p>P标签1, child 1</p>
            <div>DIV标签1, child 2</div>
            <div>DIV标签2, child 3</div>
            <p>P标签2, child 4</p>
            <div>DIV标签3, child 5</div>
            <div>DIV标签4, child 6</div>
            <p>P标签3, child 7</p>
        </div>
        <div class="t2">
            This is t2.
            <p>P标签1, child 1</p>
            <div>DIV标签1, child 2</div>
            <div>DIV标签2, child 3</div>
            <p>P标签2, child 4</p>
            <div>DIV标签3, child 5</div>
            <div>DIV标签4, child 6</div>
            <p>P标签3, child 7</p>
        </div>
    </div>
</body>
</html>
测试2结果
.test :nth-child(even) { color: red; }
测试3结果
.test :nth-child(2n+1) { color: green; }
测试4结果
上一篇 下一篇

猜你喜欢

热点阅读