方法:1、利用“父元素:nth-child(n)”选择器,该选择器会选择父元素中的第n个子元素,并且元素类型没有限制;2、利用“父元素:nth-of-type(n)”选择器,该选择器也会选择父元素中的第n个子元素,但只选择同级兄弟元素。
本教程操作环境:windows10系统、CSS3&&HTML5版本、Dell G3电脑。
1、:nth-child(n)
:nth-child(n) 选择器匹配父元素中的第 n 个子元素,元素类型没有限制。
n 可以是一个数字,一个关键字,或者一个公式。
立即学习“前端免费学习笔记(深入)”;
示例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <style> p:nth-child(3) { 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><b>注意:</b> Internet Explorer 8 and以及更早版本的浏览器 :nth-child()选择器.</p> </body> </html>
输出结果:
2、: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(3) { 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>
输出结果:
(学习视频分享:css视频教程)
以上就是css3选择器怎么选第几个的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号