3

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>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Dolphin
  • 29,069
  • 61
  • 260
  • 539
  • As you can see from [existing questions](https://www.google.com/search?q=textarea+max+rows+site%3Astackoverflow.com&rlz=1) limiting height by _row_ isn't really possible. You can easily do `max-height` in pixels if you can make that work. – isherwood May 24 '23 at 14:49

2 Answers2

2

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.

Wimanicesir
  • 4,606
  • 2
  • 11
  • 30
2

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>
Adam
  • 5,495
  • 2
  • 7
  • 24