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个孩子,它不管里面孩子是否属于同一类型
->

猜你喜欢

转载自blog.csdn.net/weixin_44079801/article/details/106968100
今日推荐