Home > OS >  How to specify a different styling for every textarea line?
How to specify a different styling for every textarea line?

Time:08-28

I need a textarea able set a different background color for each line, i have used the ::first-line pseudo-element, but how do i change the styling of another lines?

#field{
  height: 100px;
  width: 200px;
}

#field::first-line{
  background-color: #f33;
}
<textarea id='field'>
I want this to be red.
This to be green.
This to be blue and keep the same if there is not enough space.
And this another color.
</textarea>

CodePudding user response:

A textarea cannot be a "block" container, you can't emulate this behavior with CSS.

CodePudding user response:

I have used a div as backdrop with the same style as the textarea, but added transparency to the textarea background.This way the style added to the backdrop can be seen.

backdropInput()
backdropScroll()

function backdropInput(){
    backdropStyle();
    backdrop.innerHTML = "";
    let colors = ['#f33', '#3f3', '#66f'];
    let i = 0
    for(section of field.value.split("\n")){
        backdrop.innerHTML  = "<span style='background-color: " colors[i] "'>" section "</span><br>"
        i < colors.length-1 ? i   : i = 0
    }
}

function backdropScroll(){
  backdrop.scrollTop = field.scrollTop;
}

function backdropStyle(){
  let css = window.getComputedStyle(field);
    let cssstring = "";
    for (let i = 0; i < css.length; i  ) {
        cssstring  =(css[i]  ': ' css.getPropertyValue(css[i]) ";");
    }
    backdrop.style = cssstring;
    backdrop.style.position = 'absolute';
    backdrop.style.zIndex = '-1'
    backdrop.style.overflow = 'hidden';
    backdrop.style.backgroundColor = '#fff';
    backdrop.style.fontColor ='#f00';
    backdrop.style.resize = 'none';
}

//=================================================================================
//=================================================================================

//textarea resize

document.getElementById("field").addEventListener("mousedown", function(){
  backdrop.style.display = 'none'
})
document.getElementById("field").addEventListener("mouseup", function(){
    backdropStyle();
});
#field{
  height: 200px;
  width: 200px;
  background-color: rgba(0, 0, 0, 0);
}
<div id="backdrop"></div>
<textarea id='field' oninput="backdropInput()" onscroll="backdropScroll()">
This is red.
This is green.
This is blue and keep the same if there is not enough space.
This is red.
This is green.
This is blue and keep the same if there is not enough space.
And the colors keep looping
</textarea>

  • Related