用 ::before 和 ::after 添加装饰性内容
在做按钮或标签的时候,经常会看到小角标、箭头或者发光边框。这些效果不用额外加 HTML 标签,靠伪元素就能实现。比如给一个提示标签加个小红点:
.tag {
position: relative;
padding-right: 20px;
}
.tag::after {
content: '';
position: absolute;
width: 8px;
height: 8px;
background: red;
border-radius: 50%;
right: 5px;
top: 50%;
transform: translateY(-50%);
}
生成动态引号或图标
写博客类页面时,引用文字通常会加上引号。与其手动输入“”,不如用伪元素自动加上,还能统一风格。
<blockquote class="quote">这里是一段引文</blockquote>
.quote::before {
content: '“';
font-size: 1.5em;
color: #666;
}
.quote::after {
content: '”';
font-size: 1.5em;
color: #666;
}
清除浮动的老办法
虽然现在 Flex 和 Grid 已经很普及,但维护老项目时还会遇到浮动布局。用伪元素清浮动是个经典做法。
.clearfix::after {
content: '';
display: table;
clear: both;
}
制作简单图形
想画个三角形箭头?不用图片,也不用 Canvas。一个空的伪元素配合边框就能搞定。
.arrow-down::after {
content: '';
width: 0;
height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid #000;
position: absolute;
top: 10px;
right: 10px;
}
增强表单交互反馈
输入框获得焦点时,可以利用伪元素添加光晕或下划线动画。视觉效果更细腻,用户也能立刻感知当前操作位置。
.input-wrapper {
position: relative;
}
.input-wrapper::after {
content: '';
position: absolute;
bottom: -2px;
left: 0;
width: 0;
height: 2px;
background: #007acc;
transition: width 0.3s;
}
.input-wrapper:focus-within::after {
width: 100%;
}
隐藏元素但仍保留在可访问性中
有些文本对屏幕阅读器重要,但不想显示在页面上。可以用伪元素配合 clip 方法保留语义。
.sr-only::before {
content: attr(data-label);
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}