一、nth-of-type
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>nth-of-type与nth-child的区别</title>
<style>
p:nth-child(3){
color: red;
}
</style>
</head>
<body>
<p>这是p标签1</p>
<p>这是p标签2</p>
<p>这是p标签3</p>
<p>这是p标签4</p>
<span>这是span标签1</span>
<span>这是span标签2</span>
<span>这是span标签3</span>
</body>
</html>
nth-child:该选择器选择父元素标签下面的第几个子元素(只要符合父元素的选择器要求)
效果
二、nth-of-type
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>nth-of-type与nth-child的区别</title>
<style>
/* p:nth-child(5){
color: red;
} */
.item:nth-of-type(3){
color: red;
}
</style>
</head>
<body>
<p class="item">这是p标签1</p>
<p class="item">这是p标签2</p>
<p class="item">这是p标签3</p>
<p>这是p标签4</p>
<span class="item">这是span标签1</span>
<span class="item" >这是span标签2</span>
<span class="item">这是span标签3</span>
</body>
</html>
上面的列子是同为class为item的第三个元素,不管是p标签还是span标签,只要他们都有class等于item的类名,就都可以显示红色
效果
列子二:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>nth-of-type与nth-child的区别</title>
<style>
/* p:nth-child(3){
color: red;
} */
/* .item:nth-of-type(3){
color: red;
} */
p:nth-of-type(1),p:nth-of-type(3){
color: red;
}
</style>
</head>
<body>
<p class="item">这是p标签1</p>
<p class="item">这是p标签2</p>
<p class="item">这是p标签3</p>
<p>这是p标签4</p>
<span class="item">这是span标签1</span>
<span class="item" >这是span标签2</span>
<span class="item">这是span标签3</span>
</body>
</html>
效果:
nth-of-type(n)选择器,选择器选取父元素的第n个指定类型的子元素,按照类型来选择
还有一种情况:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>nth-of-type与nth-child的区别</title>
<style>
/* p:nth-child(3){
color: red;
} */
/* .item:nth-of-type(3){
color: red;
} */
/* p:nth-of-type(1),p:nth-of-type(3){
color: red;
} */
p:nth-child(3n+1){
color: red;
}
</style>
</head>
<body>
<h1>大标题</h1>
<p>这是p标签1</p>
<p>这是p标签2</p>
<p>这是p标签3</p>
<p>这是p标签4</p>
<!-- <span class="item">这是span标签1</span>
<span class="item" >这是span标签2</span>
<span class="item">这是span标签3</span> -->
</body>
</html>
效果:
我试的效果并没有像网上说的那个,H1大标签页显示红色???网上说大标签会显示红色,不应该不显示吗??
p:nth-child(3n+1) : n标签自然数从0开始,表示第1、第4、第7…
nth-of-type(3n+1)
p:nth-of-type(3n+1){
color: red;
}
</style>
</head>
<body>
<h1>大标题</h1>
<p>这是p标签1</p>
<p>这是p标签2</p>
<p>这是p标签3</p>
<p>这是p标签4</p>
<!-- <span class="item">这是span标签1</span>
<span class="item" >这是span标签2</span>
<span class="item">这是span标签3</span> -->
</body>
效果
nth-child(n) n的参数可以说odd(偶数)even(奇数)
列子:
p:nth-child(odd){
color: red;
}
</style>
</head>
<body>
<h1>大标题</h1>
<p>这是p标签1</p>
<p>这是p标签2</p>
<p>这是p标签3</p>
<p>这是p标签4</p>
<!-- <span class="item">这是span标签1</span>
<span class="item" >这是span标签2</span>
<span class="item">这是span标签3</span> -->
</body>
</html>
效果:
nth-child(even) 奇数
例子:
p:nth-child(even){
color: red;
}
</style>
</head>
<body>
<h1>大标题</h1>
<p>这是p标签1</p>
<p>这是p标签2</p>
<p>这是p标签3</p>
<p>这是p标签4</p>
<!-- <span class="item">这是span标签1</span>
<span class="item" >这是span标签2</span>
<span class="item">这是span标签3</span> -->
</body>
效果