Home > Web Front-end > CSS Tutorial > How Can I Auto-Scale a Text Input's Width to Match Its Content Length?

How Can I Auto-Scale a Text Input's Width to Match Its Content Length?

Barbara Streisand
Release: 2024-12-13 06:13:13
Original
395 people have browsed it

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template