属性选择器

属性选择器可以根据元素特定的属性来选择元素,这样就可以不借助类选择器或id选择器。

css
1
2
3
4
5
6
7
8
9
E[att]  —— 选择具有att属性的网页元素。

E[att="val"] —— 选择具有att属性且属性值**等于**val的网页元素。

E[att^="val"] —— 匹配具有att属性且属性值以val**开头**的网页元素。

E[att$="val"] —— 匹配具有att属性且属性值以val**结尾**的网页元素。

E[att*="val"] —— 匹配具有att属性且属性值**含有**val的网页元素。

示例

html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!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>css3属性选择器</title>
<style>
button {
cursor: pointer;
}
button[att1] {
color:blue;
}
button[att2='att2'] {
color:blueviolet;
}
button[att3^='start'] {
color:brown;
}
button[att4$='end'] {
color:burlywood;
}
button[att5*='center'] {
color:chartreuse;
}
</style>
</head>
<body>
<button>按钮</button>
<button att1>按钮</button>
<button att2="att2">按钮</button>
<button att3="start11">按钮</button>
<button att4="11end">按钮</button>
<button att5="11center22">按钮</button>
</body>
</html>

结构伪类选择器

结构伪类选择器主要根据文档结构来选择元素,常用于根据父级选择里面的子元素。

css
1
2
3
4
5
6
E:first-child —— 匹配父元素中第一个子元素E。
E:last-child —— 匹配父元素中最后一个子元素E。
E:nth-child(n) —— 匹配父元素中第n个子元素E。
E:first-of-type —— 指定类型 E 的第一个。
E:last-of-type —— 指定类型 E 的最后一个。
E:nth-of-type(n) —— 指定类型 E 的第n个。

代码示例

css
1
2
3
4
5
6
7
8
9
10
11
12
.dome div:first-child{
background: grey;
}
.dome div:last-child{
background: grey;
}
.dome div:nth-child(2n){
background: grey;
}
.dome div:nth-of-type(2n){
background: grey;
}

n可以是数字、关键字(even 偶数 odd奇数)、公式(2n偶数、2n+1奇数、5n倍数、n+5从5开始到最后、-n+5前5个)。

区别:

E:nth-child(n)对父元素里面的所有孩子排序选择,先找到第n个孩子,然后看是否和E匹配。
E:nth-of-type(n)对父元素里面指定子元素进行排序选择,先匹配E,然后根据E找到第n个孩子。

伪元素选择器

伪元素选择器可以帮助我们利用CSS创建标签元素,而不需要HTML标签。

css
1
2
::before —— 在元素内部的**前面**插入内容。
::after —— 在元素内部的**后面**插入内容。

语法:element::before{}

注意:

before和after创建的元素属于行内元素

新创建的元素在文档树是找不到的,所以称为伪元素。

before和after必须有content属性

代码示例

html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<head>
<style>
p::before {
content: '《绝句》--杜甫';
font-size: 22px;
font-weight: 700;
font-family: '宋体';
color: red;
}
</style>
</head>
<body>
<p>两个黄鹂鸣翠柳,一行白鹭上青天。</p>
</body>

<head>
<style>
p::after {
content: '----《绝句》杜甫';
font-size: 22px;
font-weight: 700;
font-family: '宋体';
color: green;
}
</style>
</head>
<body>
<p>两个黄鹂鸣翠柳,一行白鹭上青天。</p>
</body>