Search code examples
javascripthtmlcssinline

How to color wrapped lines with multiple color in html and js?


I have this div element in witch I want to set different color for every wrapped line.

With cl.style.display = "inline"; Reacts = cl.getClientRects(); I'm able to get top, left, right and bottom of every line

I then tried to set colors using

background: linear-gradient(...); and box-shadow:..; 

so far without any success.

A little help would really be appreciated.

.cl {
    width: 500px;
    height: fit-content;
    min-height: 18px;
    position: relative;
    overflow: hidden;

    display: inline-block;
    padding: 2px;
    white-space: pre-wrap;
    word-break: break-word;
}
<div class="cl">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div>
   

[what I want]

image: https://i.sstatic.net/w2WRY.png

Solution

  • This should achieve the effect you want by using the repeating-linear-gradient I define a variable in css to make it simple, but if it confuses you, you could directly write it.

    *I doesn't apply the css you want, but I think it is very easy for your to achieve: )

    div {
      --spacing: 2em;
      line-height: var(--spacing);
      background-image: repeating-linear-gradient(red 0 var(--spacing), green var(--spacing) calc(var(--spacing) * 2), blue var(--spacing) calc(var(--spacing) * 3), transparent var(--spacing) calc(var(--spacing) * 4));
    }
    <div>Stack Overflow is a question and answer website for professional and enthusiast programmers. It is the flagship site of the Stack Exchange Network,[4][5][6] created in 2008 by Jeff Atwood and Joel Spolsky.[7][8] It features questions and answers on a
      wide range of topics in computer programming.[9][10][11] It was created to be a more open alternative to earlier question and answer websites such as Experts-Exchange. Stack Overflow was sold to Prosus, a Netherlands-based consumer internet conglomerate,
      on 2 June 2021 for $1.8 billion.[12]</div>