如何为 html 或 css 中的文本创建自定义下划线或突出显示?

How can I create custom underline or highlight for text in html or css?

我正在尝试了解如何为文本创建自定义背景效果。 换句话说,我怎样才能做这样的事情:

尝试调整线条大小。行高。然后突出显示文本。

对于这些,我通常使用一个 SVG 像素(一个 1x1 可拉伸 HTML 编码的 SVG,带有填充颜色),我们可以随心所欲地操纵它:

h1 {
  background: url("data:image/svg+xml;charset=utf8,%3Csvg version='1.1' xmlns='http://www.w3.org/2000/svg' x='0px' y='0px' width='1px' height='1px' viewBox='0 0 1 1' preserveAspectRatio='none'%3E%3Crect x='0' y='0' width='1' height='1' fill='red' /%3E%3C/svg%3E") no-repeat 100% 100%;
  background-size: 100% 50%;
}
<h1>My Text</h1>

这还允许轻松添加动画。但是,这仅适用于单行项目。你可以改变svg fill属性里面的颜色。如果经过编码,它可以在 IE9+ 上运行,所以它非常兼容!请记住,十六进制颜色前面的哈希符号也需要编码 - 它的 %23(我个人使用 sass 为我编码)。

使用<mark> element并调整行高

mark {
  display: inline-block;
  line-height: 0em;
  padding-bottom: 0.5em;
}
<h1><mark>Lorem ipsum</mark></h1>

一篇非常好的文章解释了一种使用渐变的好方法:https://thirtyeightvisuals.com/blog/low-highlight-heading-links-squarespace

.highlight {
  background: linear-gradient(180deg,rgba(255,255,255,0) 50%, #FFD0AE 50%);
}

您可以使用 linear-gradient 设置为背景 属性 来轻松实现此目的。

CSS

.low-highlight {
  background:linear-gradient(180deg, transparent 60%, yellow 60%);
}

HTML

<p>You can easily <span class="low-highlight">do underline</span> me.</p>

p {
font-size:68px;
  font-weight:600;
  font-family:'Merriweather';
}


.low-highlight {
  background:linear-gradient(180deg, transparent 60%, yellow 60%);
}
<p>You can easily <span class="low-highlight">do underline</span> me.</p>