CSS选择器是CSS中用于选择HTML元素并应用样式规则的核心机制。下面我将详细讲解各种CSS选择器的用法和特点。
基础选择器
1. 元素选择器
通过HTML元素名称选择元素
2. 类选择器
通过class属性选择元素
1 2 3 4
| .my-class { font-size: 16px; }
|
3. ID选择器
通过id属性选择元素
1 2 3 4
| #header { background-color: #f0f0f0; }
|
4. 通用选择器
选择所有元素
1 2 3 4 5
| * { margin: 0; padding: 0; }
|
组合选择器
5. 后代选择器
选择某个元素内部的所有指定后代元素
6. 子元素选择器
选择某个元素的直接子元素
1 2 3 4
| div > p { color: green; }
|
7. 相邻兄弟选择器
选择紧接在另一个元素后的元素
1 2 3 4
| h1 + p { margin-top: 0; }
|
8. 通用兄弟选择器
选择某个元素之后的所有兄弟元素
1 2 3 4
| h1 ~ p { color: purple; }
|
属性选择器
9. 存在属性选择器
选择具有指定属性的元素
1 2 3 4
| [target] { border: 1px solid black; }
|
10. 属性值选择器
选择具有指定属性和值的元素
1 2 3 4
| [type="text"] { background-color: yellow; }
|
11. 属性值包含选择器
选择属性值包含指定字符串的元素
1 2 3 4
| [class*="btn"] { padding: 10px; }
|
12. 属性值起始选择器
选择属性值以指定字符串开头的元素
1 2 3 4
| [href^="https"] { color: green; }
|
13. 属性值结束选择器
选择属性值以指定字符串结尾的元素
1 2 3 4
| [src$=".jpg"] { border: 2px solid red; }
|
伪类选择器
14. 状态伪类
基于元素状态选择
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
| a:hover { color: orange; }
input:focus { border-color: blue; }
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
li:nth-child(odd) { background-color: #f9f9f9; }
li:nth-child(3n) { color: red; }
|
15. 表单伪类
1 2 3 4 5 6 7 8 9
| input:checked { background-color: green; }
input:disabled { opacity: 0.5; }
|
伪元素选择器
16. 内容伪元素
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| p::first-line { font-weight: bold; }
p::first-letter { font-size: 2em; }
p::before { content: "→ "; }
p::after { content: " ←"; }
::selection { background-color: yellow; }
|
选择器组合与优先级
组合使用
1 2 3 4 5 6 7 8 9
| button.btn-primary:hover { background-color: #007bff; }
h1, h2, h3 { font-family: Arial, sans-serif; }
|
优先级计算
CSS选择器优先级按以下规则计算:
- ID选择器: 100分
- 类选择器、属性选择器、伪类: 10分
- 元素选择器、伪元素: 1分
- 通用选择器: 0分
1 2
| #header .nav li a:hover {} div.container p {}
|
实际应用示例
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
| <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>CSS选择器示例</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } .card { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 5px; } [data-category="important"] { border-left: 4px solid red; } .card:hover { box-shadow: 0 2px 5px rgba(0,0,0,0.2); } .card > h3 { margin-top: 0; color: #333; } .card p:first-of-type { font-weight: bold; } h2 + .card { background-color: #f9f9f9; } .card::before { content: "📌 "; } </style> </head> <body> <h1>CSS选择器演示</h1> <h2>重要事项</h2> <div class="card" data-category="important"> <h3>重要通知</h3> <p>这是一个重要的卡片内容。</p> <p>详细信息在这里。</p> </div> <div class="card"> <h3>普通通知</h3> <p>这是一个普通的卡片内容。</p> </div> </body> </html>
|
总结
CSS选择器提供了强大的元素定位能力,掌握各种选择器的用法可以帮助你:
- 精确选择需要样式化的元素
- 创建更简洁、可维护的CSS代码
- 实现复杂的样式效果
- 提高开发效率