CSS结构伪类选择器
结构伪类选择器,可以根据元素在文档中所处的位置,来动态选择元素,从而减少HTML文档对ID或类class的依赖,有助于保持代码干净整洁。
表 — 结构伪类选择器
选择器 | 功能描述 | 版本 |
---|---|---|
E:last-child | 选择父元素的倒数第一个子元素E,相当于E:nth-last-child(1) | |
E:nth-child(n) | 选择父元素的第n个子元素,n从1开始计算 | |
E:nth-last-child(n) | 选择父元素的倒数第n个子元素,n从1开始计算 | |
E:first-of-type | 选择父元素下同种标签的第一个元素,相当于E:nth-of-type(1) | |
E:last-of-type | 选择父元素下同种标签的倒数第一个元素,相当于E:nth-last-of-type(1) | |
E:nth-of-type(n) | 与:nth-child(n)作用类似,用作选择使用同种标签的第n个元素 | |
E:nth-last-of-type | 与:nth-last-child作用类似,用作选择同种标签的倒数第一个元素 | |
E:only-child | 选择父元素下仅有的一个子元素,相当于E:first-child:last-child或E:nth-child(1):nth-last-child(1) | |
E:only-of-type | 选择父元素下使用同种标签的唯一子元素,相当于E:first-of-type:last-of-type或E:nth-of-type(1):nth-last-of-type(1) | |
E:empty | 选择空节点,即没有子元素的元素,而且该元素也不包含任何文本节点 | |
E:root | 选择文档的根元素,对于HTML文档,根元素永远HTML |
实例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--可以避免使用class,id选择器-->
<title>结构伪类选择器</title>
<style>
/* E:first-child ul的第一个子元素*/
ul li:first-child{
background:red;
}
/* E:last-child ul的最后一个子元素*/
ul li:last-child{
background:green;
}
/* E:nth-child(n) 选择父元素的第n个子元素,n从1开始计算*/
p:nth-child(2){
background:blue;
}
/* E:nth-of-type(n) 与:nth-child(n)作用类似,用作选择使用同种标签的第n个元素*/
p:nth-of-type(1){
background:yellow;
}
</style>
</head>
<body>
<h1>h1</h1>
<p>p1</p>
<p>p2</p>
<p>p3</p>
<ul>
<li>l1</li>
<li>l2</li>
<li>l3</li>
</ul>
</body>
</html>