Due to the fact that the HTML <textarea>
element does not automatically grow to fit its content, many developer look for plugins and scripts to enable this feature. This bit of JavaScript will cause any applicable <textarea>
elements to resize automatically to fit the content typed or pasted into it.
The code has the following features:
- Uses a hidden clone element (a
<div>
) that has the same typographical properties as the<textarea>
- Has no dependencies (e.g. jQuery)
- Will autosize any
<textarea>
that has a class oftxta
- Works in all browsers, even old IE
Here’s the HTML:
<textarea placeholder="Type multiple lines of content here." class="txta"></textarea>
Code language: HTML, XML (xml)
Here’s the CSS:
.txta {
width: 100%;
max-width: 500px;
min-height: 100px;
font-family: Arial, sans-serif;
font-size: 16px;
overflow: hidden;
line-height: 1.4;
}
Code language: CSS (css)
And the JavaScript (commented):