nth选择器详解

本文深入讲解了CSS中各种选择器的使用方法,包括:first-child、:last-child、:nth-child()、:nth-last-child()、:nth-of-type()、:nth-last-of-type()、:first-of-type和:last-of-type等,通过实例展示了如何精准地选择和样式化HTML元素。

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

先来认识几个常用的

  • :first-child选择某个元素的第一个子元素
  • :last-child选择某个元素的最后一个子元素
  • :nth-child()选择某个元素的一个或多个特定的子元素
  • :nth-last-child()选择某个元素的一个或多个特定的子元素,从这个元素的最后一个子元素开始算
  • :nth-of-type()选择指定的元素
  • :nth-last-of-type()选择指定的元素,从元素的最后一个开始计算
  • :first-of-type选择一个上级元素下的第一个同类子元素
  • :last-of-type选择一个上级元素的最后一个同类子元素

实例

基础代码:

    <title>nth选择器</title>
    <style>
        .box1 p{
            background-color: red;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="box1">
        <p>111</p>
        <p>222</p>
        <p>333</p>
        <p>444</p>
        <p>555</p>
    </div>
</body>
</html>

在这里插入图片描述
以下前两个示例都是基于这个html

1. :first-child

代码:

.box1 p:first-child{
	background-color: blue;
}

结果:
在这里插入图片描述
last-child与它相反,选择的是最后一个

2. :nth-child()

代码:

.box1 p:nth-child(2){
    background-color: blue;
}

结果:
在这里插入图片描述
代码:

.box1 p:nth-child(2n + 1){ // n表示从零开始的自然数
    background-color: blue;
}

结果:
在这里插入图片描述
nth-last-child()与它相反,从最后一个开始算起

3. :nth-of-type()

下面的示例都是基于这个html

代码:

    <style>
        .box1 p{
            background-color: red;
            margin-top: 20px;
        }
        .box1 h1:nth-of-type(2n + 1){
            background-color: blue;
        }
    </style>
</head>
<body>
    <div class="box1">
        <h1>h111</h1>
        <h1>h222</h1>
        <h1>h333</h1>
        <p>111</p>
        <p>222</p>
        <p>333</p>
        <p>444</p>
        <p>555</p>
    </div>
</body>
</html>

结果:
在这里插入图片描述
代码:

.box1 p:nth-of-type(2n + 1){
    background-color: blue;
}

结果:
在这里插入图片描述
:nth-last-of-type()从最后一个算起

4. :first-of-type

代码:

.box1 h1:first-of-type{
    background-color: blue;
}

结果:
在这里插入图片描述
代码:

.box1 p:first-of-type{
    background-color: blue;
}

结果:
在这里插入图片描述
:last-of-type选择最后一个

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值