一、结构伪类选择器–查找单个
1. 作用与优势
1.作用:根据元素在HTML中的结构关系查找元素
2.优势:减少对于HTML中类的依赖,有利于保持代码整洁
2.选择器
选择器 | 说明 |
---|
li:fist-child { } | 匹配父元素中第一个子元素,并且是 li 元素 |
li:last-child { } | 匹配父元素中最后一个子元素,并且是 li 元素 |
li:nth-child(n) { } | 匹配父元素中第n个子元素,并且是 li 元素 |
li:nth-last-child(n) { } | 匹配父元素中倒数第(n)子元素,并且是 li 元素 |
<!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: blue;
}
li:last-child {
background-color: red;
}
li:nth-child(3) {
background-color: green;
}
li:nth-last-child(3) {
background-color: pink;
}
</style>
</head>
<body>
<div >
<ul>
<li>我是一个标签</li>
<li>我是一个标签</li>
<li>我是一个标签</li>
<li>我是一个标签</li>
<li>我是一个标签</li>
<li>我是一个标签</li>
<li>我是一个标签</li>
</ul>
</div>
</body>
</html>
二、结构伪类选择器–查找多个
选择器 | 说明 |
---|
li:nth-child(n) { } | 匹配父元素中第n个子元素,并且是 li 元素 |
- 括号内填写 n 结果为:0、1、2、3、4、5、6…
- 通过 n 可以组成常见公式
功能 | 公式 |
---|
偶数 | 2n、even |
奇数 | 2n+1、2n-1、odd |
找到前5个 | -n+5 |
找到从第5个往后 | n+5 |
li:nth-child(-n+5) {
background-color: pink;
}
三、伪元素
- 伪元素:一般页面中的非主体内容可以使用伪元素。
- 必须设置 content 属性才能生效。
- 伪元素默认是行内元素(不能设置宽高)
- 种类:
伪元素 | 作用 |
---|
::before | 在父元素内容的最前添加一个伪元素 |
::after | 在父元素内容的最后添加一个伪元素 |
<!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>
.father {
height: 300px;
width: 300px;
background-color: skyblue;
}
.father::after {
display: block;
content: '我是伪元素';
width: 100px;
height: 100px;
background-color: green;
}
</style>
</head>
<body>
<div class="father">
我是father内部的内容
</div>
</body>
</html>