Auto-stretch textarea to fit its content (JavaScript)
Auto-stretching HTML form textarea to fit its content. That is, dynamically adjusting its vertical dimensions in JavaScript:
JavaScript code:
<script>
var textareas = document.querySelectorAll('textarea');
for ( var textarea of textareas ) {
textarea.addEventListener( 'input', function () {
this.style.height = '';
this.style.height = this.scrollHeight + parseFloat( window.getComputedStyle(this).getPropertyValue('border-width') ) * 2 + 'px';
});
}
</script>
HTML code:
<div class="example">
<form>
<textarea rows="3" placeholder="Enter your text ..."></textarea>
</form>
</div>
CSS code:
/* The key CSS properties forming vertical dimensions of the text and the right initial height of textarea */
form textarea{height: auto; font-family: roboto, Arial, Helvetica, 'Helvetica Neue', sans-serif; font-size: 18px; line-height: 26px; box-sizing: border-box;}
/* Just styling the look */
form textarea{position: relative; left: 0; top: 0; width: 100%; padding: 15px 24px 19px 24px; margin: 0; float: left; color: #000; -webkit-appearance: none; resize: vertical; outline: 0; overflow: hidden; border: 2px #999 solid; background: #fff;}
- Height:auto lets calculate the right initial height of textarea based on the value of the rows HTML attribute and font-family, font-size, line-height CSS properties. So that the subsequent JavaScript calculations are done right.
- How text is positioned inside textarea in respect to its edges is adjusted by the padding CSS property.
Browser support
- Windows
- Edge 12.0+
- Firefox 21.0+
- Google Chrome 1.0+
- Opera 12.1+
- Linux
- Firefox 21.0+
- Google Chrome 1.0+
- Opera 12.1+
- iOS
- Safari 2.0+
- Android
- Samsung Internet 1.0+
- Chrome Android 18.0+
- Firefox for Android 21.0+
- Opera Android 12.1+