如何为同一行内的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
相关产品推荐
相关产品推荐

