2

A <span> knows what horizontal size to be without being told. It's horizontal size is no greater than its content.

I'm trying to figure out the CSS to make an <input type='text'> automatically size itself horizontally according to the length of its value, like a <span> would with its innerText.

In other words, without specifying a CSS width: or size attribute on the <input>.

I can't figure out how to do this. Any ideas?

core
  • 32,451
  • 45
  • 138
  • 193

2 Answers2

3

If you want to expand or increase the width of input field as you type you could do something like this

<div>
    <span contenteditable="true">sdfsd</span>
</div>

CSS

span{
    border: solid 1px black;
}
div{
    max-width: 200px;   
}

JSFiddle Demo

Or You could accomplish this using some jQuery

<input size="1" />

jQuery

$('input').on('keydown', function(evt) {
    var $this = $(this),
        size = parseInt($this.attr('size'));

    if ( evt.which === 8 ) {
        // backspace
        $this.attr('size', size - 1);
    } else {
        // all other keystrokes
        $this.attr('size', size + 1);
    }
});

JSFiddle Demo

Nakib
  • 4,593
  • 7
  • 23
  • 45
-1

If I understand your question correctly, you want the span and input to be the same width no matter what, correct?

If this is the case then this is the way I would go about it:

Wrap both the span and input with a div

then,

span, input {
  display: inline-block;
  width: 100%;
}

And set your wrapping div to whatever width you want and the two elements should be aligned (automatically, no matter what) and the same width.

Daniel Jamrozik
  • 1,228
  • 2
  • 11
  • 25