nth-child和nth-of-type的区别

此博客主要展示了一段HTML代码,其中运用CSS选择器设置样式。如使用:first-of-type、:last-of-type、:nth-of-type等选择器为列表项设置背景颜色,还对比了:nth-child()和:nth-of-type()选择器的不同用法,体现了前端开发中样式设置的技巧。

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

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <style>

        ul li:first-of-type {

            background-color: pink;

        }

        ul li:last-of-type {

            background-color: pink;

        }

        ul li:nth-of-type(even) {

            background-color: skyblue;

        }

        /* :nth-child() 会把所有的盒子都排列序号 */

        /* 执行的时候先看nth-child(1) 之后回去看前面 div  */

        /* section div:nth-child(1) {

            background-color: red;

        } */

        /* :nth-of-type()先去匹配e,然后根据e找第n个孩子 */

        section div:nth-of-type(1) {

            background-color: blue;

        }

    </style>

</head>

<body>

    <ul>

        <li>第1个人</li>.

        <li>第2个人</li>

        <li>第3个人</li>

        <li>第4个人</li>

        <li>第5个人</li>

        <li>第6个人</li>

        <li>第7个人</li>

        <li>第8个人</li>

    </ul>

    <!-- 区别 -->

    <ul>

        <section>

            <p>光头强</p>

            <div>熊大</div>

            <div>熊二</div>

        </section>

    </ul>

</body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值