Reputation: 40886
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;
}
Upvotes: 5
Views: 5623
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
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