选择器与优先级

本笔记记录于2025年10月30日 周四,今天是满课

1.核心概念

选择器就是用来选中某种东西
比如:元素 类 id 属性 结构伪类 通配符
选中后就可改变他们的样式

2.解决了什么问题

提供了html所不能解决的美化这个问题的解答方式
通过调整不同属性以及运用不同的选择方式让自己的网页变得更美观

3.代码示例

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* 代码 */  
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>选择器学习</title>
<style>
* {
box-sizing: border-box;
}
.user-card {
width: 300px;
height: 200px;
border: 3px solid black;
padding: 10px 10px 10px 10px;
margin: 10px auto;
text-align: left;
}
.vip {
background-color: greenyellow;
}
.username {
color: blue;
}
.vip .username {
border: 3px solid gold;
padding: 2px;
border-radius: 4px;
}
.title {
color: gray;
}
.vip .title {
font-weight: bold;
}
.email {
color: green;
}
.vip .email {
color: gold;
}
.btn {
display: block;
width: 80px;
height: 25px;
padding: auto;
font-size: 14px;
border-radius: 3px;
transition: 0.3s background-color;
}
.follow-btn {
background-color: rgb(0, 195, 255);
}
.vip .follow-btn {
background-color: pink;
}
.follow-btn:hover {
background-color: darkblue;
}
.vip .follow-btn:hover {
background-color: rgb(148, 0, 211);
}
</style>
</head>
<body>
<div class="user-card">
<h3 class="username">张三</h3>
<div class="user-info">
<p class="title">前端工程师</p>
<p class="contact">
<span class="email">zhang@example.com</span>
</p>
</div>
<button class="btn follow-btn">关注</button>
</div>

<div class="user-card vip">
<h3 class="username vip-username">李四</h3>
<div class="user-info">
<p class="title">设计总监</p>
<p class="contact">
<span class="email">li@example.com</span>
</p>
</div>
<button class="btn follow-btn">关注</button>
</div>
</body>
</html>

其实后来还有很多额外学的选择器,例如:
更多伪类选择器:hover :focus :active

交集并集选择器,并集加逗号 交集贴一起

关系选择器,加号选中下一个原色,飘号选中之后的所有元素

:nth-child :first-child :last-child,按位置选中元素 选中父元素中的第一个子元素 选中父元素中的最后一个子元素

就不往里面加代码了,自己看源文件去,写了备注的

伪元素和状态伪类还没学,后面再补

有选择器不会写一定要去看MDN文档巩固知识点

4.注意事项/常见误区

opacity是调整整个卡片的透明度,如果想让颜色变浅的话就直接使用rgb然后调整透明度
注意选择器写法规范

优先级计算规则
CSS 优先级是一个四位数系统,从左到右分别是:
内联样式(行内):style="..." (得分 $1,0,0,0$)
ID 选择器:#id (得分 $0,1,0,0$)
类、属性、伪类:.class, [attr], :hover (得分 $0,0,1,0$)
元素、伪元素:p, ::before (得分 $0,0,0,1$)
通配符:* (得分 $0,0,0,0$)
越高的得分,优先级越高。如果得分相同,后出现的样式生效。!important 优先级最高(但应尽量少用)

5.相关链接

MDN文档 CSS选择器

6.本次学习总结

学习了两个半小时,总体不错,但是因为一些原因少学了一点,比如伪元素和状态伪类
下次有时间的时候我会补上,但是这次学习就到此为止吧