2

Imagine I have the following

div{
  padding: 20px;
}
<div style="display:flex; background: gold; flex-direction: column;">
  <textarea>Do NOT expand this</textarea>
  <textarea class="expand">Expand this baby</textarea>

</div>

I want when content on textarea "expand" creates vertical overflow for it to expand parent div, not to create vertical scroll.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
CommonSenseCode
  • 23,522
  • 33
  • 131
  • 186

1 Answers1

3

I think this cannot be done with only CSS, and since you don't want a jQuery one, so here is a pure JS solution. The idea is to calculate the height (resize) the textarea each time you update the content

var tex = document.querySelector('textarea.expand');

tex.addEventListener('keydown', resize);

function resize() {
  setTimeout(function() {
    tex.style.height = 'auto'; //needed when you remove content so we reduce the height
    tex.style.height = tex.scrollHeight + 'px';
  }, 0);
}
div {
  padding: 20px;
}
<div style="display:flex; background: gold; flex-direction: column;">
  <textarea>Do NOT expand this</textarea>
  <textarea class="expand">Expand this baby</textarea>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415