css - nth-child

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		p {
			height: 20px;
			margin: 10px 0 0;
			background: #ccc;
		}
		p:first-child {
			margin: 0;
		}
		div {
			width: 1000px;
			padding: 10px;
			margin: 0 auto 20px;
			box-shadow: 0 0 1px #666;
			border-radius: 5px;
		}

		.t1 p:nth-child(2),
		.t1 p:nth-of-type(2),

		.t2 :nth-child(even),

		.t3 :nth-child(odd),

		.t4 :first-child,
		.t4 :last-child,

		.t5 :nth-child(-n+3),
		.t5 :nth-last-child(-n+3),

		.t6 :only-child,

		.t7 :empty,

		.t8 :not(:empty),

		p[class|=icon],

		.bro+p,
		.aft~p {
			background: skyblue;
		}
	</style>
</head>
<body>
	<div class="t1">
		<p>p</p>
		<p>p:nth-child(2), 匹配任意标签(可指定匹配标签, 但顺序依然从第一个标签开始)</p>
		<p>p:nth-of-type(2), 匹配指定标签(顺序从指定匹配标签开始, 没有指定匹配标签, 则以第一个标签为指定标签)</p>
	</div>

	<div class="t2">
		<p>p</p>
		<p>:nth-child(even), 匹配偶数项, 或 :nth-child(2n)</p>
		<p>p</p>
		<p>p</p>
	</div>

	<div class="t3">
		<p>:nth-child(odd), 匹配奇数项, 或 :nth-child(2n-1)</p>
		<p>p</p>
		<p>p</p>
		<p>p</p>
	</div>

	<div class="t4">
		<p>:first-child, 最前一个, 或 :first-of-type</p>
		<p>p</p>
		<p>:last-child, 最后一个, 或 :last-of-type</p>
	</div>

	<div class="t5">
		<p>p</p>
		<p>p</p>
		<p>:nth-child(-n+3), 最前3个, 或 p:nth-of-type(-n+3)</p>
		<p>p</p>
		<p>:nth-last-child(-n+3), 最后3个, 或 p:nth-last-of-type(-n+3)</p>
		<p>p</p>
		<p>p</p>
	</div>

	<div class="t6">
		<p>:only-child, 仅一个元素, 或 :only-of-type</p>
	</div>

	<div class="t7">
		<p></p>
		<p>:empty, 空内容</p>
	</div>

	<div class="t8">
		<p></p>
		<p>:not(), 非</p>
	</div>

	<div>
		<p class="icon-a b">[class|=icon], class以icon为前缀. icon需要在其它类名前</p>
		<p class="b icon-a"></p>
	</div>

	<div>
		<p>前一个元素</p>
		<p class="bro">.bro+p, 匹配该元素相邻的后一个元素</p>
		<p>后一个元素</p>
		<p>后N个元素</p>
	</div>

	<div>
		<p>前一个元素</p>
		<p class="aft">.aft~p, 匹配该元素后面的所有指定元素</p>
		<p>后一个元素</p>
		<p>后N个元素</p>
	</div>

	<div>
		<h2>参考文献</h2>
		<p><a href="https://www.w3.org/TR/css3-selectors/" target="_blank">https://www.w3.org/TR/css3-selectors/</a></p>
	</div>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/NaShiShiWo/article/details/81207189