CSS 中的易碎彩色下划线

Breakable colored underline in CSS

我想要一个彩色下划线,它在断开时看起来像这样:

text-decoration-color 似乎没有得到足够广泛的支持。

我试过这个:

.underline {
  position: relative;
 }

.underline:after {
  position: absolute;
  content: '';
  height: 1px;
  background-color: #ffc04d;
  bottom: .1rem;
  right: 0;
  left: 0;
  z-index: -1;
}
 <h1><span class="underline">Sprouted Bread</span></h1>

如果 linear-gradient 可以轻松控制单个元素内的颜色、大小和距离:

.underline {
  position: relative;
  font-size:28px;
  background:
    linear-gradient(yellow,yellow) /* Color */
    left 0 bottom 2px/ /* Position */
    100% 2px  /* Size (width height)*/
    no-repeat;
 }
<div style="width:150px;text-align:center"><span class="underline">Sprouted Bread</span></div>

作为旁注,border-bottom 与 内联元素 一起使用效果很好,但当然你不能轻易控制距离以使其表现得像 text-decoration:

.underline {
  position: relative;
  font-size:28px;
  border-bottom:2px solid yellow;
 }
<div style="width:150px;text-align:center"><span class="underline">Sprouted Bread</span></div>

Try this JSFiddle

通过像在跨度中一样包装元素。您可以将文本装饰放在父元素上,将文本颜色放在跨度上。

HTML:

<h1><span class="underline">Some Text</span></h1>

CSS:

h1 {
  text-decoration: underline;
  color: red;
}

.underline {
  color: blue;
}

只需添加一个边框!

使用 display: inline,添加底部边框并 space 添加填充。

您也可以使用 line-height,然后放置负边距以增加行与行之间的 space。

而且...您还可以制作动画!

.underline {
  position: relative;
  padding-bottom: 1px;
  border-bottom: 1px solid #ffc04d;
}
<h1 style="width: 5em">
  <span class="underline">Sprouted Bread</span>
</h1>

如@chriskirknielsen 所述,您可以使用 box-decoration-break, although not supported by IE or Edge 致谢:@Temani Afif