我们可以通过限定元素自身所在的父元素的位置来实现不同的效果,主要通过的伪类型选择器是:
:first-child;
:last-child;
:first-nth-child;
:last-nth-child;
:nth-child(expression);
:nth-of-type(expression;
:nth-last-of-type(expression);
:first-of-type;
:last-of-type;
:only-child;

下面通过一个简单的示例来熟悉一下这些选择器:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <title>Structural Pseudo Class</title>
    <style>
        td {
            width: 500px;
        }

        tr {
            text-align:center;
            height: 50px;
        }

        tr:first-child {
            background-color: #486a8e;
        }

        tr:nth-child(2) {
            background-color: #dbdd84;
        }

        tr:nth-child(3n) {
            background-color: #C9E1F4;
        }

        tr:nth-last-child(2) {
            background-color: darkgreen;
        }

        tr:last-child {
            background-color: #dd6149;
        }

        tr:only-child {
            font-size: 40px;
            color:green;
            font-weight: bolder;
        }

        td:only-child {
            width: 1000px;
        }

        div > p:nth-of-type(1) {
            color: red;
        }

        div > p:nth-last-of-type(1) {
            color:blue;
        }

        section > p:first-of-type {
            background-color: #C9E1F4;
        }

        section > p:last-of-type {
            background-color: #ffa9f8;
        }
    </style>
</head>
<body>
    <h1>Structural Pseudo Class 测试</h1>
    <table>
        <tr>
            <td>A</td>
            <td>B</td>
        </tr>
        <tr>
            <td>C</td>
            <td>D</td>
        </tr>
        <tr>
            <td>E</td>
            <td>F</td>
        </tr>
        <tr>
            <td>G</td>
            <td>H</td>
        </tr>
        <tr>
            <td>I</td>
            <td>J</td>
        </tr>
    </table>

    <h2>only-child 和nth-of-type测试</h2>
    <table>
        <tr><td colspan="2">No Record</td></tr>
    </table>

    <div>
        <p>AAAAAAAAAA</p>
        <section>
            <p>A11111111111</p>
            <p>A22222222222</p>
            <p>A33333333333</p>
        </section>
        <p>BBBBBBBBBBBBBBB</p>
    </div>
</body>
</html>

效果如下:
【Css】Structural Pseudo Class(结构性伪类选择器)

相关文章:

  • 2021-11-21
  • 2022-01-12
  • 2022-12-23
  • 2021-11-30
  • 2021-06-01
  • 2022-12-23
  • 2023-04-03
  • 2022-01-06
猜你喜欢
  • 2022-12-23
  • 2021-04-24
  • 2019-01-22
  • 2021-08-07
  • 2021-12-11
  • 2022-01-30
  • 2021-11-13
相关资源
相似解决方案