The styling applied to the textarea
element in the code snippet below focuses solely on setting its width
, with no need for an initial height specification. The CSS property overflow
is not deemed necessary either, as the designated scrollHeight
takes care of displaying content that may exceed the visible area:
It represents the total height of an element's content, inclusive of any overflowed materials not currently displayed.
For further information about scrollHeight, refer to MDN documentation.
In cases where Internet Explorer compatibility is a concern, including overflow: auto
becomes essential to prevent IE from unnecessarily adding a vertical scrollbar when there's no scrolling content present.
Note that specifying the width
isn't mandatory, but it typically remains a commonly manipulated property within this context.
The accompanying JavaScript script is as follows:
document.addEventListener("DOMContentLoaded", function(event) {
var ta = document.getElementById('ta');
ta.style.height = ta.scrollHeight + 'px';
});
Upon the DOM completing loading, the textarea's height
is automatically adjusted to match its scrollHeight
.
A complete sample page intended for testing purposes is outlined as:
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
<style>
textarea {
width: 300px;
overflow: auto;
}
</style>
</head>
<body>
<textarea id="ta">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</textarea>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var ta = document.getElementById('ta');
ta.style.height = ta.scrollHeight + 'px';
});
</script>
</body>
</html>
If required, the specified code can be extended to all textareas present within the webpage:
document.addEventListener("DOMContentLoaded", function(event) {
var tas = document.getElementsByTagName('textarea');
for (var i=0; i < tas.length; i++) {
tas[i].style.height = tas[i].scrollHeight + 'px';
}
});