*新闻详情页*/>
CSS3中nth-child与nth-of-type的差别实际上很简易::nth-of-type为何要叫:nth-of-type?由于它是以"type"来区别的。也便是说:ele:nth-of-type(n)是指父元素下第n个ele元素, 而ele:nth-child(n)是指父元素下第n个元素且这个元素为ele,若并不是,则挑选不成功。
文本未免听起来较为晦涩难懂,便于了解,这里附上1个小事例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF⑻"> <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 li:nth-child(2)挑选的是<li>one</li>连接点,而.demo li:nth-of-type(2)则挑选的是<li>two</li>连接点。
可是假如在nth-child和 nth-of-type前不特定标识呢?
.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) 选定依然是第2个元素,不管它是甚么标识。而 :nth-type-of(2) 选定了两个元素,各自是父级.demo中的第2个p标识和第2个li标识,不难看出,不特定标识种类时,:nth-type-of(2)会选定全部种类标识的第2个。
大家早已掌握了nth-child和 nth-of-type的基础应用与差别,那末更进1步nth-of-type(n)与nth-child(n)中的n是甚么呢?
nth-of-type(n)与nth-child(n)中的n能够是数据、重要词或公式。 数据:也便是上面事例的应用,就不做赘述。 重要词:Odd 、even
Odd 和 even 是能用于配对下标是单数或偶数的子元素的重要词
留意:第1个子元素的下标是 1
在这里,大家为单数和偶数 p 元素特定两种不一样的情况色:
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差别的所有內容了,期待本文的內容对大伙儿学习培训或应用CSS3能有1定的协助,假如有疑惑大伙儿能够留言沟通交流。
Copyright © 2002-2020 制作小程序_小程序商城_扫码点餐小程序_微信小程序开店的步骤_牛刀小程序 版权所有 (网站地图) 粤ICP备10235580号