
使用 ::before/::after 伪元素制作特色标题样式
伪元素 ::before 和 ::after 允许在元素内容前后插入装饰性内容,无需修改 HTML 结构。以下是几种常见实现方式:
添加装饰性线条或符号
通过伪元素插入线条或符号,增强标题视觉层次:
.special-title {
position: relative;
display: inline-block;
padding: 0 20px;
font-size: 24px;
}
.special-title::before,
.special-title::after {
content: "";
position: absolute;
top: 50%;
width: 40px;
height: 2px;
background: #3498db;
}
.special-title::before {
left: -40px;
}
.special-title::after {
right: -40px;
}
实现双色标题效果
通过伪元素叠加实现文字部分颜色变化:
.colorful-title {
position: relative;
font-size: 32px;
color: #e74c3c;
}
.colorful-title::after {
content: attr(data-text);
position: absolute;
left: 0;
top: 0;
width: 50%;
overflow: hidden;
color: #2980b9;
}
HTML 需配合 data-text 属性:
<h1 class="colorful-title" data-text="特色标题">特色标题</h1>
创建背景装饰块
为标题添加背景形状提升设计感:
.block-title {
position: relative;
padding: 10px 15px;
z-index: 1;
}
.block-title::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #f1c40f;
transform: skewX(-15deg);
z-index: -1;
opacity: 0.7;
}
实现标签式标题
模拟标签贴纸效果:
.tag-title {
position: relative;
display: inline-block;
padding: 8px 30px 8px 15px;
background: #2ecc71;
color: white;
clip-path: polygon(0 0, 85% 0, 100% 50%, 85% 100%, 0 100%);
}
.tag-title::after {
content: "NEW";
position: absolute;
right: 8px;
top: 50%;
transform: translateY(-50%);
font-size: 0.7em;
opacity: 0.8;
}
关键注意事项
- 必须设置
content属性(空字符串亦可)伪元素才会生效 - 相对定位的父元素需设置
position: relative - 通过
z-index控制堆叠顺序 - 使用
attr()可以获取 HTML 属性值 - 伪元素默认是行内元素,可改为
display: block/inline-block
通过组合这些技巧,可以创建出各种独特视觉效果,同时保持 HTML 结构简洁。
&spm=1001.2101.3001.5002&articleId=152211511&d=1&t=3&u=4675a6d9b386409191eae14163301843)
1万+

被折叠的 条评论
为什么被折叠?



