How to make the size of the input match what is inside it? That is, if the number has reached 100, then the input expands.

No matter how it is done - via CSS or JS .

Here we are talking about the input type = "number" Do not confuse with other issues.

 input { width:30px; } input[type=number]::-webkit-inner-spin-button { opacity:1; } span { padding:2px; border:1px solid #ccc; } 
 <input type="number" value="10" /> <br> Пример:<br> <span class="10">10</span><br><br> <span class="100">100</span> 

  • Maybe there is something similar, if necessary without js. On js do spit it up - Mr. Black
  • This is generally not the case. This is about type = "number" - Sauron
  • Well, yes, the number pattern does not work - Mr. Black
  • Something like this jsfiddle.net/m2vgawkk/12 for reasons of toster.ru/q/222136 - Visman
  • @Visman; Yes, what you need is jsfiddle.net/m2vgawkk/14 , thanks !. - Sauron

2 answers 2

enter image description here

Js solution

 input { width: 32px; } 
 <input type='number' value='99' oninput='style.width = (value.length * 7 + 20) + "px"'> 

  • When changing the font, you need to change the constants. Yes, and with the sign - there is a problem. - Petr Chalov
  • @PetrChalov, yes, only 7 is enough to change to a size equal to one character of the font number - Mr. Black
  • size equal to one character number of the font - the width of the numbers may be different - Grundy
  • @Grundy, maybe, but nothing is said about the font in question - Mr. Black

As an option, when entering, insert all the text into a hidden container, take its width and write in styles to the input field.

 var number = document.querySelector('input'), box = document.querySelector('span'); number.oninput = function(){ this.style.width = 15 + getTextWidth(this.value) + 'px'; } function getTextWidth(text){ box.innerHTML = text; return box.offsetWidth; } 
 input { min-width:30px; font-family: Arial,"Helvetica Neue",Helvetica,sans-serif; font-size:16px; } span { font-family: Arial,"Helvetica Neue",Helvetica,sans-serif; font-size:16px; opacity:0; } 
 <input type="number"> <span></span> 

  • Each example has the right to life) - Mr. Black