You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS设置h2标签上下线性渐变边框 实现底部反向渐变

上下渐变边框反向实现方案

原有实现的核心问题是border-image会将同一张渐变素材应用到所有指定边框,无法单独为上下边框配置不同渐变方向,以下是两种可行实现:

方案一:伪元素独立控制(推荐,灵活性最高)

直接删除原有h2的border相关属性,用两个伪元素分别生成顶部、底部的渐变条,各自配置独立的渐变方向。

完整代码

h2 {
  position: relative;
  text-transform: uppercase;
  font-size: 16px;
  color: blue;
  line-height: 36px;
  letter-spacing: 1.6px;
  margin-right: 80px;
  /* 上下内边距避免文字与渐变条重叠,数值对应边框厚度 */
  padding: 3px 0;
}
/* 顶部渐变条:保留原有渐变方向 */
h2::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background: linear-gradient(90deg, orange, rgba(253, 142, 41, 0));
}
/* 底部渐变条:渐变方向反向 */
h2::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 3px;
  background: linear-gradient(90deg, rgba(253, 142, 41, 0), orange);
}

原有HTML无需修改,保持如下即可:

<div class='bloc-content-lower-upper'>
  <h2>Découvrir la technologie</h2>
  <h2>Test</h2>
</div>

方案二:拼接渐变的border-image实现

如果不想使用伪元素,可以将上下两个反向渐变拼接为同一张素材,再通过border-image的slice参数分别分配给上下边框。

修改后的h2 CSS(仅需替换原有border相关属性)

h2 {
  position: relative;
  text-transform: uppercase;
  font-size: 16px;
  color: blue;
  line-height: 36px;
  letter-spacing: 1.6px;
  margin-right: 80px;
  border-style: solid;
  border-width: 3px;
  /* 拼接渐变:上半部分为顶部边框的正渐变,下半部分为底部边框的反向渐变 */
  border-image: linear-gradient(
    to bottom,
    linear-gradient(90deg, orange, rgba(253, 142, 41, 0)) 50%,
    linear-gradient(90deg, rgba(253, 142, 41, 0), orange) 50%
  ) 100% 0 100% 0 / 3px 0 3px 0 stretch;
}

内容的提问来源于stack exchange,提问作者DUTTOO Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.30 17:06:05