序号选择器

538 阅读1分钟

序号选择器

:first-child表示“选择第一个子元素

:last-child表示”选择最后一个子元素

:nth-child()表示”选择任意一个

nth-child(an+b)表示选择b,a+b,2a+b;

nth-child(2n+1)相当于nth-child(odd)

nth-child(2n)相当于nth-child(even)

:nth-of-type()表示以某一特定标签进行排序进行索引.

:nth-last-child()表示以倒顺序进行排列。

:nth-last-of-child()表示以倒顺序进行同标签索引

使用序号选择器时被选择元素与上一级元素不能使用关系选择器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            /* 设置边框 */
            border:2px solid black;
        }
        .box1 p:first-child {
            color:blue;
        }
        .box2 p:last-child {
            color:red;
        }
        .box3 p:nth-child(3) {
            color:yellow;
        }
        p:nth-child(4) {
            color:cyan;
        }
        .box1 p:nth-last-child(1){
            color:orange;
        }
        .box1 p:nth-of-type(6) {
            color:deeppink;
        }
        .box1 p:nth-last-of-type(5) {
            color:lawngreen;
        }
        /* .box2 p:nth-child(odd) {
            color:slateblue;
        } */
        .box2 p:nth-child(even) {
            color:slateblue;
        }
        .box3 p:nth-child(3n+1) {
            color:yellowgreen;
        }
    </style>
</head>
<body>
    <div class="box1">
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <p>4</p>
        <p>5</p>
        <h6>6</h6>
        <h6>7</h6>
        <p>8</p>
        <p>9</p>
    </div>
    <div class="box2">
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <p>4</p>
        <p>5</p>
        <p>6</p>
        <p>7</p>
        <p>8</p>
        <p>9</p>
    </div>
    <div class="box3">
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <p>4</p>
        <p>5</p>
        <p>6</p>
        <p>7</p>
        <p>8</p>
        <p>9</p>
    </div>
</body>
</html>