• 技术文章 >web前端 >前端问答

    css中nth的用法是什么

    长期闲置长期闲置2022-04-27 18:34:39原创183

    nth用法:1、“:nth-child(n)”匹配第n个子元素;2、“:nth-last-child(n)”倒数匹配第n个子元素;3、“:nth-of-type(n)”匹配同类第n个子元素;4、“:nth-last-of-type(n)”。

    本教程操作环境:windows10系统、CSS3&&HTML5版本、Dell G3电脑。

    css中nth的用法是什么

    1、:nth-child(n)

    :nth-child(n) 选择器匹配父元素中的第 n 个子元素,元素类型没有限制。

    n 可以是一个数字,一个关键字,或者一个公式。

    示例如下:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8"> 
    <title>123</title> 
    <style> 
    p:nth-child(2)
    {
    background:#ff0000;
    }
    </style>
    </head>
    <body>
    <h1>这是一个标题</h1>
    <p>这是第一个段落。</p>
    <p>这是第二个段落。</p>
    <p>这是第三个段落。</p>
    <p>这是第四个段落。</p>
    <p><b>注意:</b> Internet Explorer 8 以及更早版本的浏览器不支持 :nth-child()选择器.</p>
    </body>
    </html>

    输出结果:

    04.png

    2、:nth-last-child(n)

    :nth-last-child(n) 选择器匹配属于其元素的第 N 个子元素的每个元素,不论元素的类型,从最后一个子元素开始计数。

    n可以是一个数字,一个关键字,或者一个公式。

    示例如下:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8"> 
    <title>123</title> 
    <style> 
    p:nth-last-child(2)
    {
    background:#ff0000;
    }
    </style>
    </head>
    <body>
    <p>The first paragraph.</p>
    <p>The second paragraph.</p>
    <p>The third paragraph.</p>
    <p>The fourth paragraph.</p>
    <p><b>注意:</b> Internet Explorer 8 以及更早版本的浏览器不支持:nth-last-child()选择器.</p>
    </body>
    </html>

    输出结果:

    05.png

    3、:nth-of-type(n)

    :nth-of-type(n)选择器匹配同类型中的第n个同级兄弟元素。

    n可以是一个数字,一个关键字,或者一个公式。

    示例如下:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8"> 
    <title>123</title> 
    <style> 
    p:nth-of-type(2)
    {
    background:#ff0000;
    }
    </style>
    </head>
    <body>
    <h1>This is a heading</h1>
    <p>The first paragraph.</p>
    <p>The second paragraph.</p>
    <p>The third paragraph.</p>
    <p>The fourth paragraph.</p>
    </body>
    </html>

    输出结果:

    06.png

    4、:nth-last-of-type(n)

    :nth-last-of-type(n)选择器匹配同类型中的倒数第n个同级兄弟元素。

    n 可以是一个数字,一个关键字,或者一个公式。

    示例如下:

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8"> 
    <title>123</title> 
    <style> 
    p:nth-last-of-type(2)
    {
    background:#ff0000;
    }
    </style>
    </head>
    <body>
    <h1>This is a heading</h1>
    <p>The first paragraph.</p>
    <p>The second paragraph.</p>
    <p>The third paragraph.</p>
    <p>The fourth paragraph.</p>
    <p><b>注意:</b> Internet Explorer 8以及更早版本的浏览器不支持:nth-last-of-type() 选择器.</p>
    </body>
    </html>

    输出结果:

    07.png

    (学习视频分享:css视频教程

    以上就是css中nth的用法是什么的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:css
    上一篇:jquery怎么移除多个class 下一篇:css中可以定义变量吗
    VIP课程(WEB全栈开发)

    相关文章推荐

    • 【腾讯云】年中优惠,「专享618元」优惠券!• css3新增了哪三种边框效果• div css的布局较table布局有什么优点• css3怎么实现鼠标隐藏效果• css怎么取消无序列表的显示样式类型• CSS样式就近原则是什么
    1/1

    PHP中文网