css中的序号选择器

本文介绍了CSS中的序号选择器,包括:first-child用于选择第一个子元素,:nth-child()和:nth-of-type()用于按序号选择特定子元素,:nth-last-child()和:nth-last-of-type()则用于倒数选择。通过这些选择器,可以精确地定位和样式化页面中的元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1、:first-child:表示选择第一个子元素,如 .box1 p:first-child 表示选择box盒子中的第一个p

 2、:nth-child():表示选择任意序号的子元素,如 .box2 p:nth-child(3)表示选择box2盒子中的第三个p。另外nth-child还可以写成an+b的形式,如 .box2 p:nth-child(3n+2)表示从第二个p开始,每三个p选择一个 ps:2n+1等价于odd及奇数,2n等价于even及偶数

 3、:nth-of-type:表示选择同种标签指定序号的子元素,

 

如 .box3  p:nth-of-type(3)表示box中p类型的第三个p

4、:nth-last-child():表示倒数选择

5、:nth-last-of-type():表示倒数选择

 

<!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>
        .box1 p:first-child{
            color: blue;
        }
        .box2 ul.nick li:nth-child(2){
            color: brown;
        }
        .box2 ul.jack li:nth-child(odd){
            color: burlywood;
        }
        .box3 p:nth-of-type(4){
            color: chartreuse;
        }
        .box4 p:nth-last-child(1){
            color: cyan;
        }
        .box5 p:nth-last-of-type(3){
            font-style: italic;
        }
    </style>
</head>
<body>
     <div class="box1">
        <!-- :first-child示例 -->
        <p>我是p标签</p>
        <p>我是p标签</p>
        <p>我是p标签</p>
    </div>
    <div class="box2">
        <!-- :nth-child()示例 -->
        <ul class="nick">
            <li>1</li>
            <li>2</li>
            <li>3</li>
        </ul>
        <ul class="jack">
            <li>1</li>
            <li>1</li>
            <li>1</li>
        </ul>
    </div>
    <div class="box3">
        <!-- :nth-of-type()示例 -->
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <h3>4</h3>
        <h3>5</h3>
        <p>6</p>
        <p>7</p>
    </div>
    <div class="box4">
        <!-- :nth-last-child()示例 -->
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <p>4</p>
    </div>
    <div class="box5">
        <!-- :nth-last-of-type()示例 -->
        <p>1</p>
        <p>2</p>
        <p>3</p>
        <h3>4</h3>
        <h3>5</h3>
        <p>6</p>
        <p>7</p>
    </div>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值