I am filling a textarea with content for the user to edit.
Is it possible to make it stretch to fit content with CSS (like overflow:show
for a div)?
I am filling a textarea with content for the user to edit.
Is it possible to make it stretch to fit content with CSS (like overflow:show
for a div)?
Here is a function that works with jQuery (for height only, not width):
function setHeight(jq_in){
jq_in.each(function(index, elem){
// This line will work with pure Javascript (taken from NicB's answer):
elem.style.height = elem.scrollHeight+'px';
});
}
setHeight($('<put selector here>'));
Note: The op asked for a solution that does not use Javascript, however this should be helpful to many people who come across this question.
This is a very simple solution, but it works for me:
<!--TEXT-AREA-->
<textarea id="textBox1" name="content" TextMode="MultiLine" onkeyup="setHeight('textBox1');" onkeydown="setHeight('textBox1');">Hello World</textarea>
<!--JAVASCRIPT-->
<script type="text/javascript">
function setHeight(fieldId){
document.getElementById(fieldId).style.height = document.getElementById(fieldId).scrollHeight+'px';
}
setHeight('textBox1');
</script>
Alternatively, you could use a contenteditable
element, this will fit to the text inside.
<div contenteditable>Try typing and returning.</div>
Please note that it's not possible to send this value along in a form, without using some javascript. Also contenteditable
will possibly generate HTML-content and allows styling, so this may need to be filtered out upon form submit.
Answers here were good but were lacking a piece of code that I had to add to avoid a shrinking that is not welcome when you type for the first time :
var $textareas = $('textarea');
$textareas.each(function() { // to avoid the shrinking
this.style.minHeight = this.offsetHeight + 'px';
});
$textareas.on('input', function() {
this.style.height = '';
this.style.height = this.scrollHeight + 'px';
});
Not 100% related to the question as this is for Angular only.
There is a npm package associated with Angular called @angular/cdk (if using Angular Material Design). There is a property included in this package that can be associated to a textarea called cdkTextareaAutosize. This automatically sets the textarea to 1 line and stretches the textarea to fit the content accordingly. If you are using this library, something like this should work.
<textarea
maxLength="200"
cdkTextareaAutosize
type="text">
</textarea>