美文网首页
CSS学习----结构伪类选择器(nth-child、nth-o

CSS学习----结构伪类选择器(nth-child、nth-o

作者: 扮猪老虎吃 | 来源:发表于2020-11-05 20:45 被阅读0次

    结构伪类选择器

    作用

    根据文档结构来选择器元素。

    语法

    E:first-child       匹配父元素中的第1个子元素E
    E:last-child        匹配父元素中的最后1个子元素E
    E:nth-child(n)      n指定具体数值匹配父元素中的第n个子元素E
    E:nth-child(n)      n,匹配父元素中的所有子元素E
    E:nth-child(2n)     2n,匹配父元素中的所有偶数元素E
    E:nth-child(2n+1)   2n+1,匹配父元素中的所有奇数元素E
        可以设置n的表达式
        n+5 从第五个开始一直到后面的所有
        -n+5, 前五个
    E:nth-child(even)   匹配父元素中的所有偶数元素E
    E:nth-child(odd)    匹配父元素中的所有奇数元素E
    

    注意
    nth-child

    • nth-child会把所有的盒子都排列序号
    • 执行的时候先看:nth-child, 再看前面的E。

    nth-of-type

    • nth-of-type 会把指定元素的盒子排列序号
    • 执行的时候会先看 指定的元素E 之后会去看:nth-of-type(n) 第n个孩子 */

    示例说明

    <!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>
            /* nth-child 会把所有盒子都排列序号 */
            /* 执行的时候会先看 :nth-child(1)之后会去看 前面的div */
            section div:nth-child(1) {
                background-color: red;
                color: yellow;
            }
            /* nth-of-type 会把指定元素的盒子排列序号 */
            /* 执行的时候会先看 div指定的元素  之后会去看 :nth-of-type(1) 第1个孩子 */
            section div:nth-of-type(1) {
                background-color: blue;
                color: yellow;
            }
        </style>
    </head>
    <body>
        <section>
            <p>光头强</p>
            <div>熊大</div>
            <div>熊二</div>
        </section>
    </body>
    </html>
    

    效果

    相关文章

      网友评论

          本文标题:CSS学习----结构伪类选择器(nth-child、nth-o

          本文链接:https://www.haomeiwen.com/subject/dpiavktx.html