首页 > 解决方案 > 使用 css 或 js 突出显示一半高度的文本

问题描述

我需要像黄线那样做。 在此处输入图像描述

我知道使用<span><p>可以模仿标记效果。但我需要这个标记不是全文高度,必须是 1/2 或 1/3 高度。(如图)

我尝试使用伪类(之前和之后),但仍然失败。

请给我一些提示!

标签: javascriptcsshighlight

解决方案


我能想到的最简单和最快的方法是使用linear-gradient“半填充”你的背景:

.half_background {
  background: linear-gradient(to top, yellow 50%, transparent 50%);
}
<p>Some text, <span class="half_background">some other text with half background</span>.</p>

⋅ ⋅ ⋅</p>

然后,我们可以很容易地扩展它来做一些其他的事情:

p {
  background-color: #eee;
  margin: 0.4em 0;
  padding: 0.6em;
}

.half_background {
  background: linear-gradient(to top, var(--bot) 50%, var(--top) 50%);
}
<p>Some text, <span class="half_background" style="--top: transparent; --bot: yellow;">some other text with half background</span>.</p>
<p>Some text, <span class="half_background" style="--top: orange; --bot: transparent;">some other text with half background</span>.</p>
<p>Some text, <span class="half_background" style="--top: violet; --bot: cyan;">some other text with half background</span>.</p>


推荐阅读