Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set input width to fit text size

Tags:

css

I have and input with icon, looking like this: screenshot

<div class="input-with-icon">
  <input type="text" value="abcdefeghijklmnopqrtvuvwxyz" class="form-control">
  <span class="icon icon-calendar"></span>
</div>

live demo

Is it possible to adjust CSS so the input will always fit the text width? e.g. it will stretch as I type.

currently, .input-with-icon has fixed width, but if I set it to auto, input won't stretch.

like image 686
Liero Avatar asked Nov 27 '22 19:11

Liero


1 Answers

<input id="txt" type="text" value="Hello World!" />
input {
min-width:50px!important;
max-width:99.99%!important;
transition: width 0.25s;
text-align:center;
}
function resizable (el, factor) {
var int = Number(factor) || 7.7;
function resize() {el.style.width = ((el.value.length+1) * int) + 'px'}
var e = 'keyup,keypress,focus,blur,change'.split(',');
for (var i in e) el.addEventListener(e[i],resize,false);
resize();
}
resizable(document.getElementById('txt'),7);
like image 97
Ankit Tajpara Avatar answered Nov 29 '22 13:11

Ankit Tajpara