CSS 选择器
基本概念
- 选择器是
CSS 中的关键部分,用来选中指定元素并为其设置样式。
- 常见优先级可以先记为:
ID 选择器 > 类选择器 > 标签选择器。
常见选择器类型
- 元素选择器
- 类选择器
- ID 选择器
- 通用选择器
- 子元素选择器
- 后代选择器
- 相邻兄弟选择器
- 伪类选择器
元素选择器
类选择器
1 2 3
| .highlight { background-color: yellow; }
|
ID 选择器
1 2 3 4
| #header { font-size: 24px; color: blue; }
|
通用选择器
1 2 3 4
| * { font-family: "kaiTi"; font-weight: bolder; }
|
子元素选择器
1 2 3 4
| .father > .son { color: yellowgreen; font-size: 35px; }
|
后代选择器
1 2 3
| .father p { color: brown; }
|
相邻兄弟选择器
1 2 3
| h3 + p { color: orange; }
|
伪类选择器
1 2 3 4
| #element:hover { color: paleturquoise; font-size: 30px; }
|
补充说明
:first-child 选中第一个子元素
:last-child 选中最后一个子元素
:nth-child(n) 选中第 n 个子元素
:active 选中正在被点击的元素
伪元素选择器
::before 在元素内容之前插入内容
::after 在元素内容之后插入内容
课堂完整示例代码
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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>6.CSS选择器</title> <style> h2{ color: green; } .highlight { background-color: yellow; } #header { font-size: 24px; color: blue; } *{ font-family: 'kaiTi'; font-weight: bolder; }
.father >.son { color: yellowgreen; font-size: 35px; } .father p{ color: brown; }
h3 + p { color: orange; }
#element:hover { color: paleturquoise; font-size: 30px; }
</style> </head> <body> <h1>不同类型的 CSS 选择器</h1> <h2>这是一个元素选择器示例</h2> <h3 class="highlight">这是一个类选择器示例</h3> <h3>这是另一个类选择器示例</h3> <h4 id="header">这是一个ID选择器示例</h4>
<div class="father"> <div class="son">这是一个子元素选择器示例</div> <div> <p class="grandson">这是一个后代元素选择器示例</p> </div> </div>
<p>这是一个普通的p标签</p> <h3>这是一个相邻兄弟选择器示例</h3> <p>这是另一个p标签</p>
<h3 id="element">这是一个伪类选择器示例</h3> </body> </html>
|
知识点总结
- 选择器决定样式作用到哪些元素上。
- 常见优先级可以先记为:
ID 选择器 > 类选择器 > 标签选择器。
- 关系选择器经常考察:子元素选择器、后代选择器、兄弟选择器。
- 伪类选择器主要描述元素状态,伪元素主要用于插入额外内容。
复习表达
CSS 选择器用于选中页面中的目标元素并添加样式。常见的有标签选择器、类选择器、ID 选择器、通用选择器,以及子元素、后代、兄弟等关系选择器。基础优先级通常可以记为 ID > 类 > 标签,另外伪类选择器用于描述元素状态,伪元素选择器用于在内容前后插入额外内容。