今天小编跟大家讲解下有关CSS选择器:nth-child()和:nth-of-type()的使用 ,相信小伙伴们对这个话题应该有所关注吧,小编也收集到了有关CSS选择器:nth-child()和:nth-of-type()的使用 的相关资料,希望小伙伴们看了有所帮助。
今天就讲一下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标签而是其他的标签,那么选择的标签不成立,选择不了。
代码如下:
<div id="a1"><p>CGLweb前端</p><div>CGLweb前端</div><p>CGLweb前端</p></div><style type="text/css">#a1 p:nth-child(2){ background:#000000;}(www.gendna5.com)</style>:nth-of-type()
匹配标签选择模式,比如说代码div:nth-of-type(2n),不考虑其他的标签,先把同级div排列一下,然后2的倍数的时候选择他。
<div id="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><style type="text/css">#a2 div:nth-of-type(2n){ background:#000000; color:#fff;}</style>四、一般使用方法1、:nth-child(x); 选择第x的元素
代码:
<div><p>p1</p><p>p2</p><p>p3</p><p>p4</p><p>p5</p><p>p6</p><p>p7</p><p>p8</p></div><style type="text/css">.div1 p:nth-child(5){ background:#0086b3; color:#fff;}</style>2、:nth-child(x*n) x的n倍元素
代码:
<div><p>p1</p><p>p2</p><p>p3</p><p>p4</p><p>p5</p><p>p6</p><p>p7</p><p>p8</p></div><style type="text/css">.div2 p:nth-child(2n){ background:#0086b3; color:#fff;}</style>3、:nth-child(n+x); 选择 =>x 的元素
代码:
<div><p>p1</p><p>p2</p><p>p3</p><p>p4</p><p>p5</p><p>p6</p><p>p7</p><p>p8</p></div><style type="text/css">.div3 p:nth-child(n+3){ background:#0086b3; color:#fff;}</style>4、:nth-child(-n+x) 选择 =< x 的元素
代码:
<div><p>p1</p><p>p2</p><p>p3</p><p>p4</p><p>p5</p><p>p6</p><p>p7</p><p>p8</p></div><style type="text/css">.div4 p:nth-child(-n+3){ background:#0086b3; color:#fff;}</style>5、:nth-child(nx+1); nx-1 隔开n*x选取一个
代码:
<div><p>p1</p><p>p2</p><p>p3</p><p>p4</p><p>p5</p><p>p6</p><p>p7</p><p>p8</p></div><style type="text/css">.div5 p:nth-child(3n+1){ background:#0086b3; color:#fff;}</style>6、nth-child(odd)/nth-child(even) 奇数偶数
代码:
<div><p>p1</p><p>p2</p><p>p3</p><p>p4</p><p>p5</p><p>p6</p><p>p7</p><p>p8</p></div><style type="text/css">.div6 p:nth-child(odd){ background:#0086b3; color:#fff;}.div6 p:nth-child(even){ background:#f4b613; color:#fff;}</style>来源:爱蒂网