当前位置: 代码迷 >> 综合 >> css3中 nth-child 和 nth-of-type 的区别
  详细解决方案

css3中 nth-child 和 nth-of-type 的区别

热度:55   发布时间:2023-11-29 13:12:39.0

参考:深入理解css3中 nth-child 和 nth-of-type 的区别 - peakleo - 博客园 

首先:nth-child 和 nth-of-type的索引都是从1开始的

nth-child 和 nth-of-type有什么不同?

直接上例子,看代码注释就好

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>demo</title>
</head>
<style>/*ul下的第2个元素  且这个元素为li*/.ul li:nth-child(2) {color: red;}/*ul下的第2个li*/.ul li:nth-of-type(2) {color: green;}
</style>
<body>
<div><ul class="ul"><div>zero</div><li>one</li>    <!-- red --><li>two</li>    <!--  green--></ul>
</div>
</body>
</html>

如果在nth-child和 nth-of-type前不指定标签 

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>demo</title>
</head>
<style>/*ul下的第2个元素*/.ul :nth-child(2) {color: red;}/*ul下 的所有类型标签的第二个。*/.ul :nth-of-type(2) {color: green;}</style><body>
<div><ul class="ul"><div>first div</div><li>first li</li><!-- 红色 --><li>second li</li><!-- 绿色 --><div>second div</div><!--绿色  --><div style="padding-left:10px"><span>first span</span><span>second span</span><!--绿色  --></div></ul>
</div>
</body>
</html>

 公式:或者说是算术表达式

使用公式 (an + b)。描述:表示周期的长度,n 是计数器(从 0 开始),b 是偏移值。在这里,我们指定了下标是 3 的倍数的所有 p 元素的背景色:

<style>p:nth-of-type(3n+0) {background: #ff0000;}
</style>
 

若是 :nth-of-type(4n+2) 就是选择下标是4的倍数加上2的所有元素

  相关解决方案