css3中的nth-child(n)和nth-of-type(n
2019-05-22 本文已影响1人
jaimor
这里记录一下看着相似,用法也相似,平时会用但是有可能又用错了的这两个css3选择器。还有几个类似的,如:first-of-type
, first-child
, last-child
等。
解释
-
div:nth-child(n)
这个写法选择的是:父元素下的 第n个子元素 且 这个子元素是div 的元素。 -
div:nth-of-type(n)
这个写法选择的是:父元素下的 第n个类型为div 的元素。
注意:下标是从
1
开始。
实例
-
测试1
第一个测试,我们先来验证下上边的解释。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.test .t1 { float: left; margin-right: 50px; }
.test .t1 { float: left; }
.test .t1 div:nth-child(4) { color: red; }
.test .t1 div:nth-of-type(4) { color: green; }
.test .t2 p:nth-child(7) { color: gray; }
.test .t2 p:nth-of-type(2) { color: red; }
</style>
</head>
<body>
<div class="test">
<div class="t1">
This is t1.
<p>P标签1, child 1</p>
<div>DIV标签1, child 2</div>
<div>DIV标签2, child 3</div>
<p>P标签2, child 4</p>
<div>DIV标签3, child 5</div>
<div>DIV标签4, child 6</div>
<p>P标签3, child 7</p>
</div>
<div class="t2">
This is t2.
<p>P标签1, child 1</p>
<div>DIV标签1, child 2</div>
<div>DIV标签2, child 3</div>
<p>P标签2, child 4</p>
<div>DIV标签3, child 5</div>
<div>DIV标签4, child 6</div>
<p>P标签3, child 7</p>
</div>
</div>
</body>
</html>

-
测试2
这个测试,我们来测试下不是用标签限定,或者使用*
作为标签限定。如:.test :nth-child(3)
表示选择.test
下第3个子元素且不管这个子元素是什么。.test *:nth-of-type(3)
表示选择.test
下所有类型标签的第3个标签。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.test .t1 { float: left; margin-right: 50px; }
.test .t1 { float: left; }
.test :nth-child(3) { color: red; }
/*.test *:nth-child(3) { color: red; }*/
/*.test :nth-of-type(3) { color: green; }*/
.test *:nth-of-type(3) { color: green; }
</style>
</head>
<body>
<div class="test">
<div class="t1">
This is t1.
<p>P标签1, child 1</p>
<div>DIV标签1, child 2</div>
<div>DIV标签2, child 3</div>
<p>P标签2, child 4</p>
<div>DIV标签3, child 5</div>
<div>DIV标签4, child 6</div>
<p>P标签3, child 7</p>
</div>
<div class="t2">
This is t2.
<p>P标签1, child 1</p>
<div>DIV标签1, child 2</div>
<div>DIV标签2, child 3</div>
<p>P标签2, child 4</p>
<div>DIV标签3, child 5</div>
<div>DIV标签4, child 6</div>
<p>P标签3, child 7</p>
</div>
</div>
</body>
</html>

-
测试3
在括号中可以使用关键词,如:odd
和even
是可用于匹配下标是奇数
或偶数
的子元素。
.test :nth-child(even) { color: red; }

-
测试4
在括号中还可以使用像数学中的那种表达式an+b
的形式,如:2n
表示偶数项,2n+1
表示奇数项,以及3n+1
、5n+3
等。
.test :nth-child(2n+1) { color: green; }
