Reputation: 67330
If I have
<div><input></input></div>
how can I make the width of both the input
and the containing div
automatically as wide as the text value currently presented. In particular, I want the box to grow and shrink when the user edits the input.
Can I do is in pure CSS? Do I have to listen for events and update the style? How? (Note: the font in this case is mono-spaced, so probably that makes it easier, although I'm interested in a general solution).
Upvotes: 5
Views: 1304
Reputation: 60573
A Pure CSS solution that might help you:
you can fake theinput
by using span
then make it contenteditable="true"
which is widely supported, see here
span {
border: 1px solid black;
display: inline-block;
white-space: nowrap;
font-family: monospace
}
<span contenteditable="true"> </span>
Upvotes: 9
Reputation: 288670
You can add an input
event listener, which will run whenever the value changes.
And in that listener, update input
's size
attribute.
If the font is monospaced, it should work as desired.
document.querySelector('input').addEventListener('input', function() {
this.size = this.value.length || 1;
});
input { font-family: monospace; }
<input size="1" />
Upvotes: 2