BeetleJuice
BeetleJuice

Reputation: 40886

CSS: allow textarea to grow with contents up to a limit

On certain sites (eg Github), the textareas have a set min-height and max-height. As the user types into them, they grow with content until they reach their max height. Then vertical scroll bars appear.

How is this effect accomplished? My textarea does not grow with its contents even though it hasn't reached the specified max-height

textarea{
  width:100%;
  min-height:80px;
  max-height:200px;
  overflow:auto;
}

Look at this demo

Upvotes: 5

Views: 5623

Answers (2)

Sid Biffi
Sid Biffi

Reputation: 522

Check out this Pen.

JS

This snippet do the trick:

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

textarea.addEventListener('keydown', autosize);

function autosize(){
  var el = this;
  setTimeout(function(){
    el.style.cssText = 'height:auto; padding:0';
    // for box-sizing other than "content-box" use:
    // el.style.cssText = '-moz-box-sizing:content-box';
    el.style.cssText = 'height:' + el.scrollHeight + 'px';
  },0);
}

CSS

And i added this to the css to make it only resizable vertically:

  resize:vertical;

Upvotes: 7

roberrrt-s
roberrrt-s

Reputation: 8210

Native HTML/CSS involves faking a textarea with contenteditable. But a JavaScript/jQuery solution would probably more suitable, however: for documentation purposes:

.container{width:300px; border:1px solid blue; padding:10px}
.textarea{
  width:100%;
  min-height:80px;
  max-height:200px;
  overflow:auto;
}
<div class="container">
  <div class='textarea' contenteditable='true'>Hello world</div>
</div>

Automatically resizes when the user is entering more content due to the nature of behaving <div> elements.

Upvotes: 5

Related Questions