我们在通过CSS操作多个元素时,经常需要选择第n个子元素,给它单独设置样式,比如有一个关于用户列表的 li 列表,想把其中的第三条信息标为红色,本文简单整理了一下选择第 n 个子元素的方法。CSS3 :nth-child() 选择器不支持低版本的 IE 浏览器,针对低版本的 IE 浏览器,可以通过 jQuery 选择器来渲染。

CSS3 :nth-child() 选择器-图片1

实例:

规定属于其父元素的第二个子元素的每个 p 的背景色:

  1. p:nth-child(2) {
  2. background:#ff0000;
  3. }

请看下面的例子:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <style type="text/css">
  5. p:nth-child(2) { background:#ff0000; }
  6. </style>
  7. </head>
  8. <body>
  9. <h1>这是标题</h1>
  10. <p>第一个段落。</p>
  11. <p>第二个段落。</p>
  12. <p>第三个段落。</p>
  13. <p>第四个段落。</p>
  14. <p><b>注释:</b>Internet Explorer 不支持 :nth-child() 选择器。</p>
  15. </body>
  16. </html>

上述代码运行结果:

CSS3 :nth-child() 选择器-图片2

低版本IE浏览器可以使用JQuery的写法来支持nth-child()。

  1. $(document).ready(function(){
  2. $("p:nth-child(2)").css("background","#ff0000");
  3. });

本文已通过「原本」原创作品认证,转载请注明文章出处及链接。

WEB最后更新:2022-11-10
夏日阳光
  • 本文由 夏日阳光 发表于 2019年3月30日
  • 本文为夏日阳光原创文章,转载请务必保留本文链接:https://www.pieruo.com/47.html
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定

拖动滑块以完成验证
加载中...