<html>
<head>
</head>
<body>
<input type="text" value="1" style="min-width:1px;" />
</body>
</html>
This is my code and it is not working. Is there any other way in HTML, JavaScript, PHP or CSS to set minimum width?
I want a text input field with a dynamically changing width, so that the input field fluids around its contents. Every input has a built-in padding of 2em
, that is the problem and second problem is that min-width
ain't working on input at all.
If I set width more than it is needed than the whole program is messy, I need the width of 1px, more only if it's needed.
This is an Angular-specific answer, but this worked for me and has been very satisfying in terms of its simplicity and ease-of-use:
It automatically updates via the character units in Jani's answer.
A bullet-proof, generic way has to:
input
elementCodepen demo
Why not using just css?
this code was introduced by @Iain Todd to and I thought I should share it
Better is
onvalue
:It also involves pasting, dragging and dropping, etc.
You can set an input's width using the size attribute as well. The size of an input determines it's width in characters.
An input could dynamically adjust it's size by listening for key events.
For example
JsFiddle here
Based off Michael's answer, I have created my own version of this using jQuery. I think it is a cleaner/shorter version of most answers here and it seems to get the job done.
I am doing the same thing as most of the people here by using a span to write the input text into then getting the width. Then I am setting the width when the actions
keyup
andblur
are called.Here is a working codepen. This codepen shows how this can be used with multiple input fields.
HTML Structure:
jQuery:
The function above gets the inputs value, trims the extra spaces and sets the text into the span to get the width. If there is no text, it instead gets the placeholder and enters that into the span instead. Once it enters the text into the span it then sets the width of the input. The
+ 5
on the width is because without that the input gets cut off a tiny bit in the Edge Browser.If this could be improved please let me know as this is the cleanest solution I could come up with.