CSS3 子节点选择器

CSS3中新增了几个子元素选择器,大大提高了开发者的开发效率。之前有些要通过为一个个子元素添加class,或者js实现才能实现的效果。现在可以很方便的用选择器实现。

这些新的样式已被现代浏览器及IE9以上支持。

 选择器  说明
:first-child 第一个子元素
:last-child 最后一个子元素
:nth-child(3) 第三个子元素
:nth-last-child(3)  倒数第三个子元素
:nth-child(odd) 所有奇数个子元素
:nth-child(even) 所有偶数个子元素
div h2:nth-of-type(even) div 中所有的h2元素中,所有的偶数元素(只针对同类型子元素计算)
:nth-last-of-type 反过来计算
li:nth-child(4n+1) 循环样式 匹配第1,5,9...个li
li:nth-child(4n+2) 循环样式 匹配第2,6,10...个li
li:nth-child(4n+4) 可简写为 li:nth-child(4n)
ul li:first-child:last-child 是第一个也是最后一个,即匹配ul中只有一个li.
:only-child 上面的简写形式。匹配某个父元素只有一个子元素
   

h2:nth-child(3) 与 h2:nth-of-type(3) 的区别?

h2:nth-child(3) 指 第三个子元素中正好是h2则应用该样式

h2:nth-of-type(3) 指所有的h2子元素的合集中,对第三个h2应用该样式

<style type="text/css">
    h2:nth-child(3){
        background-color:green;
    }

    h2:nth-of-type(3){
        background-color:#e00;
    }
</style>
</head>
<body>
<div>
<h2>文章标题A</h2>
<p>文章正文。</p>
<h2>文章标题B</h2>
<p>文章正文。</p>
<h2>文章标题C</h2>
<p>文章正文。</p>
<h2>文章标题D</h2>
<p>文章正文。</p>
</div>
</body>

结果:

循环样式的使用区别?

<style type="text/css">
/*对第1,5,9个li标签应用样式*/
li:nth-child(4n+1) { background-color: yellow; }
/*对第2,6,10个li标签应用样式*/
li:nth-child(4n+2) { background-color: limegreen; } li:nth-child(4n+3) { background-color: red; } li:nth-child(4n) { background-color: #999; } </style> </head> <body> <ul> <li>列表项目1</li> <li>列表项目2</li> <li>列表项目3</li> <li>列表项目4</li> <li>列表项目5</li> <li>列表项目6</li> <li>列表项目7</li> <li>列表项目8</li> <li>列表项目9</li> <li>列表项目10</li> <li>列表项目11</li> <li>列表项目12</li> </ul> </body>

效果:

:nth-child(1)         等价于 :first-child

:nth-last-child(1)   等价于 :last-child

:first-child:last-child   等价于 :only-child

原文地址:https://www.cnblogs.com/mafeifan/p/3592342.html