在css3中有两个新的选择器可以选择父元素下对应的子元素,一个是:nth-child 另一个是:nth-of-type。 但是它们到底有什么区别呢?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
</head>
<style>
.demo li:nth-child(2){
color: #ff0000;
}
.demo li:nth-of-type(2){
color: #00ff00;
}
</style>
<body>
<div>
<ul class="demo">
<p>zero</p>
<li>one</li>
<li>two</li>
</ul>
</div>
</body>
</html>
.demo :nth-child(2){
color: #ff0000;
}
.demo :nth-of-type(2){
color: #00ff00;
}
这样又会是什么结果呢,看下html结构:
<ul class="demo">
<p>first p</p>
<li>first li</li>
<li>second li</li>
<p>second p</p>
</ul>
如上可见,在他们之前不指定标签类型,:nth-child(2) 选中依旧是第二个元素,无论它是什么标签。而 :nth-type-of(2) 选中了两个元素,分别是父级.demo中的第二个p标签和第二个li标签,由此可见,不指定标签类型时,:nth-type-of(2)会选中所有类型标签的第二个。
p:nth-of-type(odd)
{
background:#ff0000;
}
p:nth-of-type(even)
{
background:#0000ff;
}
公式:或者说是算术表达式
使用公式 (an + b)。描述:表示周期的长度,n 是计数器(从 0 开始),b 是偏移值。
在这里,我们指定了下标是 3 的倍数的所有 p 元素的背景色:
p:nth-of-type(3n+0)
{
background:#ff0000;
}
若是 :nth-of-type(4n+2) 就是选择下标是4的倍数加上2的所有元素
深入理解css3中nth-child和 nth-of-type的区别
原文:http://www.cnblogs.com/peakleo/p/6232384.html