Expand a textbox to fit its content using CSS?
3 answers
I'm trying to get the textbox to grow as needed to fit the text entered into it, up to 80% of the width of the parent div.
I'm pretty sure this is not possible with CSS alone, because CSS cannot determine the length of the text content textarea
.
With javascript on every key press you can check the length of the text content, and if:
- the text content exceeds a certain number of keystrokes; and
- width
textarea
is still narrower than the maximum allowed width
it textarea
can gradually expand.
Working example:
var myTextArea = document.getElementsByTagName('textarea')[0];
var myTextLength = myTextArea.value.length
var myTextWidth = parseInt(window.getComputedStyle(myTextArea).width);
var myTextMinLength = 20;
var myTextMaxWidth = ((parseInt(window.getComputedStyle(document.body).width) / 100) * 80);
function checkTextLength() {
myTextLength = myTextArea.value.length;
if ((myTextLength > myTextMinLength) && (myTextWidth < (myTextMaxWidth))) {
myTextWidth += 8;
}
myTextArea.style.width = myTextWidth + 'px';
}
myTextArea.addEventListener('keypress', checkTextLength, false);
textarea {
width: 180px;
height: 40px;
}
<form>
<textarea placeholder="Start typing..."></textarea>
</form>
0
source to share