Search code examples
htmlcss

Different background colors for each line in the textarea (or editable div?)


I have a textarea for user text input and I want each line to have different background color (from a predefined set of 10 colors, can be repeated if more lines). I understand that I can use CSS expressions like nth-of-type(10n+1) for the tables, static text etc. - but not sure how to implement it for the textarea content.
(attached snippet doesn't really do anything about that, it's just a template to work with)

.my1 {
  background-image:
    repeating-linear-gradient(white, white 30px, gray 31px, white 31px);
  line-height: 31px;
  padding: 8px 10px;
}
<textarea class="my1"></textarea>


Solution

  • Simply define the 10 colors inside your gradient.

    Example with 4 colors:

    .my1 {
      --l:1.5em; /* height of line  */
    
      background-image:
        repeating-linear-gradient(
         red    0                calc(var(--l)*1), 
         green  calc(var(--l)*1) calc(var(--l)*2),
         blue   calc(var(--l)*2) calc(var(--l)*3),
         purple calc(var(--l)*3) calc(var(--l)*4));
      line-height: var(--l);
      
      color:#fff;
    }
    <textarea class="my1"></textarea>

    If you want padding, you have to offset the gradient to avoid misalignment. Only an offset from the top is required

    .my1 {
      --l:1.5em; /* height of line  */
    
      background:
        repeating-linear-gradient(
         red    0                calc(var(--l)*1), 
         green  calc(var(--l)*1) calc(var(--l)*2),
         blue   calc(var(--l)*2) calc(var(--l)*3),
         purple calc(var(--l)*3) calc(var(--l)*4)) 0 8px no-repeat,
         yellow;
      line-height: var(--l);
      padding:8px 10px;
      
      color:#fff;
    }
    <textarea class="my1"></textarea>