Home >Web Front-end >CSS Tutorial >How Can I Auto-Scale a Text Input's Width to Match Its Content Length?
Auto-scaling Text Input Width to Match Value Length
Is there a way to automatically adjust the width of an to match the width of the text it contains?
Solution:
Yes, you can easily achieve this by setting the size attribute of the input to the length of the input content. Here's how you can do it using JavaScript:
function resizeInput() { $(this).attr('size', $(this).val().length); } $('input[type="text"]') // event handler .keyup(resizeInput) // resize on page load .each(resizeInput);
Demonstration:
[See JSFiddle](http://jsfiddle.net/nrabinowitz/NvynC/)
However, this method may add some padding on the right, which varies depending on the browser. To achieve a tighter fit, you can calculate the pixel width of your text using a technique like the one described in [this](https://stackoverflow.com/questions/16401893/set-width-of-input-field-to-display-values-with-fixed-width-in-chrome) Stack Overflow answer.
The above is the detailed content of How Can I Auto-Scale a Text Input's Width to Match Its Content Length?. For more information, please follow other related articles on the PHP Chinese website!