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

如何为同一行内的heading标题元素实现三种不同背景色效果

实现方案

以下两种方案都无需修改现有HTML结构,可直接复用你现有的<h3 class="heading">Heading</h3>代码:

方案1:CSS渐变实现

仅修改.heading的背景属性即可,通过线性渐变直接生成三段不同背景色,调整颜色值和占比参数即可匹配你的需求:

.heading {
    /* 三段颜色可自行替换,后面的数值对应色块的宽度范围 */
    background: linear-gradient(
        to right,
        #E63946 0 20px,
        #FFC20E 20px calc(100% - 50px),
        #1D3557 calc(100% - 50px) 100%
    );
    font-size: 23px;
    font-weight: 600;
    padding: 5px 0 5px 22px;
    font-family: "Open Sans";
    width: 100%;
}

方案2:伪元素实现

通过::before和::after伪元素生成左右两段独立背景,中间保留原有背景,适合需要单独调整侧边色块样式(如加阴影、圆角、特殊形状)的场景:

.heading {
    background-color: #FFC20E;
    font-size: 23px;
    font-weight: 600;
    padding: 5px 0 5px 22px;
    font-family: "Open Sans";
    position: relative;
    width: 100%;
}
/* 左侧色块 */
.heading::before {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    height: 100%;
    width: 20px;
    background-color: #E63946;
}
/* 右侧色块 */
.heading::after {
    content: "";
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    width: 50px;
    background-color: #1D3557;
}

两种方案都兼容所有主流浏览器,你可以根据自己需要的色块宽度、颜色替换对应参数即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:15:03