ObbyOss ObbyOss - 2 months ago 14
HTML Question

Dynamically Adjust HTML Text Input Width to Content

I can't quite find a clear answer on this, and excuse me if there is one I've missed.

I want my text input widths to automatically adjust to the size of the content within them. First with placeholder text than the actual text someone inputs.

I've created the below as an example. Currently, the boxes are far bigger than my placeholder text, causing huge amounts of white space, and it's obviously the same thing when I type in something.

I've tried width auto, some jQuery, and twine and bubble gum I found on the internet. But nothing has worked yet. Any thoughts? Thanks!


<span><p>Hello, my name is </p></span>

<span><input type="text" id="input" class="form" placeholder="name"></span>

<span><p>. I am </p></span>

<span><input type="text" id="input" class="form" placeholder="age"></span>

<span><p> years old.</p></span>


.form {
border: 0;
text-align: center;
outline: none;

span {
display: inline-block;

p {
font-family: arial;



Use onkeypress even

see this example :http://jsfiddle.net/kevalbhatt18/yug04jau/7/

<input id="txt" placeholder="name" class="form" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';"></span>

And for placeholder on load use jquery and apply placeholder size in to input

$('input').css('width',((input.getAttribute('placeholder').length + 1) * 8) + 'px');

Even you can use id instead of input this is just an example so that I used $(input)

And in css provide min-width

.form {
    border: 1px solid black;
    text-align: center;
    outline: none;


If you remove all text from input box then it will take placeholder value using focusout

Example: http://jsfiddle.net/kevalbhatt18/yug04jau/8/


        this.style.width = ((this.value.length + 1) * 8) + 'px';
      this.style.width = ((this.getAttribute('placeholder').length + 1) * 8) + 'px';