现在的位置: 首页 > web前端 > 正文

CSS选择器 nth child()和 nth of type()的使用

2020年07月14日 web前端 ⁄ 共 1065字 ⁄ 字号 评论关闭

  今天就讲一下css选择器:nth-child()和:nth-of-type()的使用。


  一、:nth-child()和:nth-of-type()的支持度


  所有主流浏览器均支持:nth-child()和:nth-of-type()选择器,除了IE8及更早的版本。


  二、:nth-child()和:nth-of-type()的一般使用方法


  1、:nth-child(x);选择第x的元素


  2、:nth-child(x*n)x的n倍元素


  3、:nth-child(n+x);选择=>x的元素


  4、:nth-child(-n+x)选择=<x的元素


  5、:nth-child(nx+1);nx-1隔开n*x选取一个


  6、nth-child(odd)/nth-child(even)奇数偶数


  使用的时候请把《*》删除


  三、:nth-child()和:nth-of-type()的一些不同之处


  :nth-child()—–》


  混合型跳过模式:这个是我自己取得名字。


  意思就是说同一个父级下如果我们选择了第二个元素p:nth-child(2)。


  但是第二个元素不是p标签而是其他的标签,那么选择的标签不成立,选择不了。


  代码如下:


  <divid="a1">


  <p>CGLweb前端</p>


  <div>CGLweb前端</div>


  <p>CGLweb前端</p>


  </div>


  <styletype="text/css">


  #a1p:nth-child(2){background:#000000


  </style>


  :nth-of-type()—–》


  匹配标签选择模式,比如说代码div:nth-of-type(2n),不考虑其他的标签,


  先把同级div排列一下,然后2的倍数的时候选择他。


  <divid="a2">


  <p>p1</p>


  <div>div1</div>


  <p>p2</p>


  <div>div2</div>


  <div>div3</div>


  <p>p3</p>


  <div>div4</div>


  <div>div5</div>


  <div>div6</div>


  </div>


  <styletype="text/css">


  #a2div:nth-of-type(2n){background:#000000;color:#fff;}


  </style>


  总之,:nth-child()和:nth-of-type()给大家简单的介绍了一些,希望大家多看看。

抱歉!评论已关闭.