如何为linear-gradient模拟的双色下划线添加圆角?
如何给background模拟的双色下划线添加圆角效果?
我用background属性模拟了双色下划线,代码如下:
background: linear-gradient( to right, $green 0%, $green 75%, $red 75%, $red ) no-repeat 0 100%; background-size: 100% 4px;
这段代码生成的下划线是直角样式,我想要实现圆角效果(当前效果为直角双色下划线,期望效果为两端带圆角的双色下划线)。
直接给元素添加border-radius属性无法生效,测试代码如下:
.line { width: 200px; height: 20px; display: table; position: relative; background: linear-gradient( to right, green 0%, /* 绿色段 */ green 75%, /* 绿色段 */ red 75%, /* 红色段 */ red /* 红色段 */ ) no-repeat 0 100%; background-size: 100% 10px; border-radius: 9999px; }
<div class="line"></div>
请问该如何实现圆角效果?
解决方案
直接给元素加border-radius不会作用于背景渐变,改用伪元素承载渐变+设置圆角即可实现需求,示例代码如下:
适配文字宽度的下划线
.underline-rounded { position: relative; display: inline-block; padding-bottom: 4px; /* 调整文字与下划线的间距 */ } .underline-rounded::after { content: ""; position: absolute; left: 0; bottom: 0; width: 100%; height: 4px; /* 下划线粗细 */ background: linear-gradient(to right, green 0%, green 75%, red 75%, red); border-radius: 9999px; /* 大数值实现完全圆角,可按需调整 */ }
<span class="underline-rounded">带圆角的双色下划线文字</span>
固定宽度的下划线
如果需要固定宽度的下划线(不跟随文字),修改父元素的display并设置宽度即可:
.underline-rounded { position: relative; display: block; width: 200px; height: 20px; /* 容器高度,按需调整 */ } .underline-rounded::after { content: ""; position: absolute; left: 0; bottom: 0; width: 100%; height: 10px; /* 下划线粗细 */ background: linear-gradient(to right, green 0%, green 75%, red 75%, red); border-radius: 9999px; }
<div class="underline-rounded"></div>
内容的提问来源于stack exchange,提问作者Malvinka
相关产品推荐
相关产品推荐

