H5中nth-child(n)详解

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>nth-child(n)</title>
    <style>
        /* n 可以是关键词。将所有下标为偶数的标签选出来 */
        /* ul li:nth-child(even) {
            background-color: #fff;
        } */
        /* n 可以是关键词。将所有下标为奇数的标签选出来 */
        /*         
        ul li:nth-child(odd) {
            background-color: rgba(138, 132, 132, 0.924);
        } */
        /* 如果n为公式,n从0开始计算 */
        /* ul li:nth-child(-n+5) {
            background-color: pink;
        } */
        
        div :nth-child(2) {
            background-color: hotpink;
        }
        /* 以下格式没有结果:因为下图表示即是span标签又是第一个标签。由结构可知
        第一个标签是p标签,因此矛盾。 */
        /* <!-- nth-child(n)在选择n时只专注于选择第几个元素标签,并不区分是否是同类型 --> */
        
        div span:nth-child(1) {
            background-color: skyblue;
        }
        /* div :nth-child(2) {
            background-color: blue;
        } */
        /* 上下这里欧昂中表示都可以将span表签的第二个选出来 */
        /* div span:nth-child(2) {
            background-color: green;
        } */
        /* 根据类型选择元素of-type */
        /* 选择span类型的第一个元素 */
        
        div span:first-of-type {
            background-color: yellow;
        }
        /* 选择span类型的最后一个元素 */
        
        div span:last-of-type {
            background-color: rgb(63, 61, 206);
        }
        /* 选择指定类型的元素nth-of-type(n),此处的n与nth-child(n)相同 */
        
        div span:nth-of-type(2) {
            background-color: lightblue;
        }
    </style>
</head>

<body>
    <!-- 由于ul里面只允许放li 标签,所以nth-child(n)和 nth-of-type(n)效果相同 -->
    <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>
        <li>9</li>
        <li>10</li>
    </ul>
    <!-- nth-child(n)在选择n时只专注于选择第几个元素标签,并不区分是否是同类型 -->
    <div>
        <p>1</p>
        <span>2</span>
        <span>3</span>
        <span>4</span>

    </div>
</body>

</html>
<!-- nth-child(n):
1.n可以是数字,关键字和公式
2.n如果是数字,表示就是选择第几个
3.常见的关键字;even(偶数)odd(奇数)
4.n如果是公式,则从0 开始计算,但是第0个元素或者
超出了元素个数会被忽略 
常见公式:
2n  偶数
2n+1 奇数
5n  
n+5 从第5 个开始(包含地5个)到最后
-n+5 前5个(包含第5)
tips:
nth-child(n)选择父元素里面的第n个孩子,它不管里面孩子是否属于同一类型
->
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值