Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize input to fit its content

I do not care for a specific technology, it could be JS, CSS or even some unstandard and evil html attributes. I just want the input to get bigger if user types over the right border.

like image 320
rsk82 Avatar asked Jan 11 '11 23:01

rsk82


People also ask

How do I make input width fit content?

Use the span. text to fit width of text, and let the input have same size with it by position: absolute to the container.

How do I resize a input box in CSS?

The simple way to make an input resize freely is to set it to it to have width: 100% , and then place it inside an inline-block container with a min-width ( min-width sets the default width for the input ). Resize the container to resize the input .

How do I change the input width?

1. Set width in HTML. In HTML, you can use the width attribute to set the width of an element. Alternatively, you can also use the size attribute to define the width of the <input> .


2 Answers

Let the browser do the calculating of the width by using a div with contenteditable set to true.

<div class="pseudo-input" contenteditable="true">Resizes to my content!</div>

There should be no issues with browser support http://caniuse.com/#feat=contenteditable

like image 173
Era Avatar answered Sep 25 '22 01:09

Era


You can also create div element, copy your input style to it and use it's dimensions to resize input. (Chosen multiple uses this solution).

var input = $('input'),
    dummy = $('<div style="position:absolute; left: -1000%;">').appendTo('body');

['font-size', 'font-style', 'font-weight', 'font-family',
 'line-height', 'text-transform', 'letter-spacing'].forEach(function(index) {
    dummy.css(index, input.css(index));
});

input.on('input', function() {
   dummy.html(this.value);
   input.width(dummy.width());
});

UPD: better to use pre instead div to follow spaces size.

like image 39
Тёма Пендюрин Avatar answered Sep 22 '22 01:09

Тёма Пендюрин