CSS伪元素选择器
伪元素选择器用于创建不在文档树中的虚拟元素,以双冒号 :: 开头。
语法格式
CSS
选择器::伪元素 {
属性: 值;
}
::before 和 ::after
CSS
/* 在元素内容前插入 */
.quote::before {
content: '"';
color: gray;
}
/* 在元素内容后插入 */
.quote::after {
content: '"';
color: gray;
}
必须设置 content 属性才会显示:
CSS
.box::before {
content: ''; /* 空内容 */
display: block;
width: 10px;
height: 10px;
background: red;
}
/* 使用图片 */
.link::after {
content: url('icon.png');
}
::first-letter
选中块级元素首字母:
CSS
p::first-letter {
font-size: 32px;
font-weight: bold;
color: red;
}
::first-line
选中块级元素首行:
CSS
p::first-line {
font-weight: bold;
color: #333;
}
::selection
选中用户选中的文本:
CSS
::selection {
background: yellow;
color: black;
}
伪元素列表
| 伪元素 | 说明 | |
|---|---|---|
::before | 元素内容前插入 | |
::after | 元素内容后插入 | |
::first-letter | 首字母 | |
::first-line | 首行 | |
::selection | 用户选中文本 | |
::placeholder | 输入框提示文本 |
实用示例
CSS
/* 清除浮动 */
.clearfix::after {
content: '';
display: block;
clear: both;
}
/* 添加图标 */
.btn::after {
content: '→';
margin-left: 8px;
}
/* 首字下沉 */
.article::first-letter {
float: left;
font-size: 48px;
line-height: 1;
margin-right: 8px;
}
/* 输入框提示样式 */
input::placeholder {
color: #999;
font-style: italic;
}
注意:伪元素权重为1,
content属性是必须的。
要点总结
::before和::after最常用,需设置content- 伪元素是虚拟元素,不在 DOM 中
- 权重为1,低于类和伪类选择器
- 可用于添加装饰、图标、清除浮动等
存放路径:articles/CSS/入门/CSS选择器/CSS伪元素选择器.md
📝 发现内容有误?点击此处直接编辑