Expand a textbox to fit its content using CSS?

I am 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.

Is there a way to do this with just CSS? If not, I'm open to Javascript solutions, but I'm using React, which complicates things in this regard.

+3


source to share


3 answers


Perhaps you can have a div inside a parent div that is 80% of the parent div. And then set the width: automatically for the textbox. It might sound a little tricky.



0


source


hm ... try this:

display: inline-block;

      



I'm not sure. Let me know if it works.

0


source


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>
      

Run codeHide result


0


source







All Articles