Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a textarea expand automatically to a maximum height?

Tags:

html

css

I am learning CSS. I have a div which contains a flexible textarea. Now I want the textarea and outer div to auto expand height when the user inputs multiline content in the textarea, and when the textarea is more than 3 rows, stop the expand and scroll the textarea. How should I write the CSS?

Rendered Code:

.outerdiv {
  height: auto;
  display: flex;
}

.outerdiv textarea {
  height: 100%;
  flex-grow: 1;
}
<div class="outerdiv">
  <textarea></textarea>
</div>
like image 615
Dolphin Avatar asked Nov 29 '25 17:11

Dolphin


2 Answers

You could adapt this absolute gem of an answer as follows:

textarea {
  height: 1rem;
}
<textarea 
  data-max-height = "48" 
  name="text" 
  oninput='this.style.height = "";this.style.height = Math.min(this.scrollHeight, this.getAttribute("data-max-height")) + "px"'
  >
</textarea>
like image 110
Adam Avatar answered Dec 02 '25 05:12

Adam


I don't think there is a css solution.

However this JS kinda does what you want:

function updateTextarea() {
   var textarea = document.getElementById("textarea");
    // Get line height of the textarea
   var lht = parseInt($('textarea').css('lineHeight'),10);
    // Get lines 
   var scrlht = textarea.scrollHeight;
   var lines = Math.floor(scrlht / lht);
   
   if (lines < 4) {
    textarea.style.height = '15px'
    textarea.style.height = (lines * lht) + 'px'
   }
 }
textarea {
line-height: 15px;
height: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <textarea id='textarea' oninput="updateTextarea()"></textarea>
</div>

It does not make the texarea smaller when removing text. But it does grow when you type.

like image 22
Wimanicesir Avatar answered Dec 02 '25 06:12

Wimanicesir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!