Search code examples
javascriptcsshighlight

use css or js highlight text with half height


I need to do like the yellow line. enter image description here

I know use <span> or <p> can imitate the mark effect. But I need this mark not to full text height, must be 1/2 or 1/3 height.(like picture)

I try to use pseudo class(before & after), but still failed.

Please give me some tips!


Solution

  • The easiest and fastest way I can think about is to use a linear-gradient to “half fill” your background:

    .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>

    ⋅ ⋅ ⋅

    Then, we can easily expand that to do some other things:

    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>