CSS3 :nth-child() 选择器

WEB评论6554字数 582阅读模式

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

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

实例:

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

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

请看下面的例子:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css"> 
        p:nth-child(2) { background:#ff0000; }
    </style>
</head>
<body>
    <h1>这是标题</h1>
    <p>第一个段落。</p>
    <p>第二个段落。</p>
    <p>第三个段落。</p>
    <p>第四个段落。</p>
    <p><b>注释:</b>Internet Explorer 不支持 :nth-child() 选择器。</p>
</body>
</html>

上述代码运行结果:

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

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

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

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

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:
确定

拖动滑块以完成验证