在日常网页设计中,有些视觉效果看似简单,但如果用传统HTML加CSS的方式实现,代码会变得臃肿。这时候,CSS伪元素就派上用场了。它们不占用额外的DOM结构,却能完成很多巧妙的布局和装饰任务。
给文字添加装饰性符号
比如文章开头的引言部分,设计师常常希望在段落前加一个引号图标。以前可能得写一个标签再加样式,现在直接用::before就行。
.quote {
position: relative;
}
.quote::before {
content: "\201C";
font-size: 2em;
color: #888;
position: absolute;
left: -10px;
top: 0;
}
制作气泡对话框
聊天界面里的气泡框,底部常有一个小三角指向说话人。这个三角其实不用图片,用::after就能画出来。
.bubble {
position: relative;
background: #007acc;
color: white;
padding: 10px;
border-radius: 8px;
max-width: 200px;
}
.bubble::after {
content: "";
position: absolute;
bottom: -10px;
left: 20px;
border: 10px solid transparent;
border-top-color: #007acc;
}
清除浮动的老办法
虽然现在有更现代的布局方式,但在维护老项目时还会遇到浮动塌陷问题。用::after配合clear属性是个经典解法。
.clearfix::after {
content: "";
display: table;
clear: both;
}
按钮悬停时的动态效果
很多网站的按钮在鼠标移上去时会有光效滑动,这种效果也可以靠伪元素实现。比如让一道亮光从左到右扫过。
.btn {
position: relative;
overflow: hidden;
background: #333;
color: white;
padding: 10px 20px;
}
.btn::before {
content: "";
position: absolute;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(
90deg,
transparent,
rgba(255,255,255,0.4),
transparent
);
transition: left 0.5s;
}
.btn:hover::before {
left: 100%;
}
隐藏元素但保留可访问性
有时候需要把某个图标文字藏起来,比如“搜索”按钮上的“放大镜”图标旁写着“搜索”,视觉上不需要显示文字,但屏幕阅读器仍需读取。用::before或::after配合text-indent或clip可以做到。
.icon-search::after {
content: "搜索";
position: absolute;
clip: rect(1px, 1px, 1px, 1px);
overflow: hidden;
height: 1px;
width: 1px;
}
这些只是常见的一部分用法。只要content属性不为空,伪元素就能生效,结合定位、变换和动画,能玩出不少花样。关键是别把它当成炫技工具,而是真正用来简化结构、提升可维护性的手段。