- HTML中文网
- 联系QQ:88526
- QQ交流群

- 微信公众号

:nth-child() 选择器
定义和用法
:nth-child(n) 选择器匹配父元素中的第 n 个子元素,元素类型没有限制。
n 可以是一个数字,一个关键字,或者一个公式。
提示: 请参阅:nth-of-type()选择器。该选择器匹配同类型中的第 n 个同级兄弟元素。
浏览器支持
表格中的数字表示支持该属性的第一个浏览器版本号。
选择器 | ![]() | ![]() | ![]() | ![]() | ![]() |
:nth-child() | 4.0 | 9.0 | 3.5 | 3.2 | 9.6 |
指定每个 p 元素匹配的父元素中第 2 个子元素的背景色:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> *{ font-size: 20px; } p:nth-child(2){ background-color:#f79578; } </style> </head> <body> <div> <p>这是第一个段落。</p> <h1>这是标题</h1> </div> <div> <p>这是第二个段落。</p> <p>这是第三个段落。</p> </div> <p>这是第四个段落。</p> </body> </html>
点击 "运行实例" 按钮查看在线实例
效果图:
推荐手册