WHAT - CSS 伪元素
目录
- CSS 伪元素(Pseudo-elements)
- 常见的 CSS 伪元素
- 1. ::before 和 ::after
- 特点
- 示例
- 2. ::first-letter 和 ::first-line
- 特点
- 示例
- 3. ::selection
- 作用
- 示例
- 4. ::placeholder
- 作用
- 示例
- 伪元素 vs 伪类
- 总结
CSS 伪元素(Pseudo-elements)
CSS 伪元素(Pseudo-elements)用于选中特定部分的元素,或创建额外的虚拟元素,以便应用样式。
伪元素以 ::
开头。
常见的 CSS 伪元素
伪元素 | 作用 |
---|---|
::before | 在元素的前面插入内容 |
::after | 在元素的后面插入内容 |
::first-letter | 选中元素的第一个字母 |
::first-line | 选中元素的第一行文本 |
::selection | 选中用户高亮(选中)的文本 |
::placeholder | 选中 input 或 textarea 的占位文本 |
1. ::before 和 ::after
::before
和 ::after
允许在元素前后插入内容,常用于装饰、图标、标签等。
特点
- 必须搭配
content
属性使用。 content
可以是文本、图片(url()
)、空字符串(用于装饰)。
/* 在 <button> 前面添加图标 */
button::before {
content: "🔥 ";
font-size: 18px;
}
/* 在 <button> 后面添加箭头 */
button::after {
content: " ➜";
font-size: 18px;
}
示例
<button>Click me</button>
渲染效果:🔥 Click me ➜
2. ::first-letter 和 ::first-line
特点
::first-letter
仅影响第一个字母。::first-line
仅影响第一行文本,受文本换行影响。
/* 让段落首字母变大并加粗 */
p::first-letter {
font-size: 24px;
font-weight: bold;
color: red;
}
/* 让段落的第一行文本变蓝色 */
p::first-line {
color: blue;
}
示例
<p>Welcome to the world of CSS! This is a test paragraph to demonstrate the first-letter and first-line pseudo-elements.</p>
渲染效果:第一行变蓝色,首字母变红色+加粗。
3. ::selection
作用
- 允许自定义用户选中的文本的样式。
/* 让选中的文本变为橙色背景,白色文字 */
::selection {
background-color: orange;
color: white;
}
示例
<p>Try selecting this text!</p>
效果:用户选中文本后,背景变橙色,文字变白色。
4. ::placeholder
作用
- 用于自定义
<input>
和<textarea>
占位符文本的样式。
input::placeholder {
color: gray;
font-style: italic;
opacity: 0.8;
}
示例
<input type="text" placeholder="Enter your name">
效果:占位符变灰色 + 斜体。
伪元素 vs 伪类
特性 | 伪类(Pseudo-class) | 伪元素(Pseudo-element) |
---|---|---|
语法 | : 开头 | :: 开头 |
作用 | 选中已有状态的元素 | 选中元素的特定部分或创建新内容 |
示例 | :hover , :nth-child(n) | ::before , ::after |
影响 | 影响整个元素 | 仅影响部分内容或额外内容 |
总结
伪元素:
::before
和::after
用于添加装饰内容,必须有content
属性。::first-letter
和::first-line
用于样式化文本的部分内容。::selection
可以自定义选中文本的颜色和背景。::placeholder
控制输入框的占位符样式。
伪类和伪元素可以结合使用,例如:
button:hover::after {
content: " ✅";
color: green;
}