skip to Main Content

Given the following text area;

<textarea textarea contentEditable="true">  
testing autoheight lkjul;khjfds
kjhkjghg

fgdgdsf
</textarea>

Is there a way I can set it height to fit the text? I’ve tried CSS;

height:auto;

But no luck

I’ve got this working with some JS;

const tx = document.getElementsByTagName("textarea");

for (let i = 0; i < tx.length; i++) {
  if (tx[i].value != ''){ 
    tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;");
  }
}

But it seems mad to me that there’s no way to do this sans JS.

I’ve noticed other questions similar to mine (like this one) but they all mention JS solutions.

Is there a non JS solution to this?

2

Answers


  1. You can set a wight and a height using the props "rows & cols" in the html

    Anyway, it’s more usefull to set this with javascript and css to make it responsive, but this is usefull to set a width and height 🙂

    For example:
    <textarea id="Lorem" name="Lorem" rows="6" cols="50">Lorem impsu </textarea>
    Login or Signup to reply.
  2. Try this:

    <textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search