伪元素实战 制作特色标题样式(before/after伪元素)​

使用 ::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 结构简洁。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值