目录
Css 结构伪类选择器
在日常开发中,结构伪类选择器用的还是比较多的熟练的使用它,可以让我们的代码更整洁。
作用与优势:
- 作用:根据元素在HTML中的结构关系查找元素。
- 优势:减少对于HTML中类的依赖,有利于保持代码的整洁,毕竟起名字也是一个难题。
- 应用场景:常用于查找某个父级选择器中的子元素。
选择器:
选择器 | 描述 |
---|---|
E:first-child {} | 匹配父元素中第一个子元素,并且是E元素 |
E:last-child {} | 匹配父元素中最后一个子元素,并且是E元素 |
E:nth-child(n) | 匹配父元素中第n个子元素,并且是E元素 |
E:nth-last-child(n) | 匹配父元素中倒数第n个子元素,并且是E元素 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 匹配父元素中第一个子元素 */
/* li:first-child {
background-color: pink;
}
*/
/* 匹配父元素中最后一个子元素 */
/* li:last-child {
background-color: pink;
} */
/* 匹配父元素中第三个子元素 */
/* li:nth-child(3) {
background-color: pink;
} */
/* 匹配父元素中倒数第n个子元素 */
li:nth-last-child(1) {
background-color: pink;
}
</style>
</head>
<body>
<ul>
<li>我是第1个li</li>
<li>我是第2个li</li>
<li>我是第3个li</li>
<li>我是第4个li</li>
<li>我是第5个li</li>
<li>我是第6个li</li>
<li>我是第7个li</li>
<li>我是第8个li</li>
</ul>
</body>
</html>
结构伪类-公式
结构伪类中的n不光可以指定元素,还可以书写公式
常见公式
功能 | 公式 |
---|---|
偶数 | 2n,even |
奇数 | 2n+1,2n-1,odd |
找到前五个 | -n+5 |
从第五个往后 | n+5 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 二的倍数 */
/* li:nth-child(2n) {
background-color: pink;
} */
/* 选中前六个元素 */
li:nth-child(-n+6) {
background-color: pink;
}
</style>
</head>
<body>
<ul>
<li>我是第1个</li>
<li>我是第2个</li>
<li>我是第3个</li>
<li>我是第4个</li>
<li>我是第5个</li>
<li>我是第6个</li>
<li>我是第7个</li>
<li>我是第8个</li>
</ul>
</body>
</html>