nth-child和nth-of-type的区别
以前一般都用:nth-child,后来知道了:nth-of-type,然后就一般用nth-of-type
它们两有什么区别呢?
首先来看个现象:
假如有这样一个HTML结构
<div class="post"> <p>我是段落1</p> <p>我是段落2</p> </div>
分别加上两个样式的效果
.post > p:nth-child(2){ background-color: red; }
![](https://images2015.cnblogs.com/blog/982650/201607/982650-20160729112846450-1584695766.png)
.post > p:nth-of-type(2){ background-color: yellow; }
![](https://images2015.cnblogs.com/blog/982650/201607/982650-20160729112950200-942753984.png)
这个时候我们发现它们的效果是一样的,那么它们的区别是什么呢?别着急,看下面这个例子
这是HTML结构:
<div class="box"> <h1>我是标题</h1> <p>我是段落1</p> <p>我是段落2</p> </div>
和案例1一样的样式加上去
.box > p:nth-child(2){ background-color: red; }
![](https://images2015.cnblogs.com/blog/982650/201607/982650-20160729113442622-1805453671.png)
.box > p:nth-of-type(2){ background-color: yellow; }
![](https://images2015.cnblogs.com/blog/982650/201607/982650-20160729113533075-1090020812.png)
如果我们把样式稍微改一下
.box > p:nth-child(1){ background-color: blue; }
![](https://images2015.cnblogs.com/blog/982650/201607/982650-20160729114315575-250887214.png)
.box > p:nth-of-type(1){ background-color: blue; }
![](https://images2015.cnblogs.com/blog/982650/201607/982650-20160729114406497-1940465271.png)
这个时候:nth-child的效果就比较出乎意料了;
通过几个案例在来说两者的区别可能好理解一点:
"p:nth-chil(n)":p的父元素的第n个子元素,如果这个元素时p类型,那么就给它加上后面的样式,如果不是那就算了
"p:nth-of-type(n)":p的父元素的p类型的子元素的第n个