Make the <input> (and the enclosing <div>) automatically as wide as the content
If I have
<div><input></input></div>
how can i make the width both input
and containing div
automatically as wide as the text value currently presented. Specifically, I want the box to grow and shrink when the user edits the input.
Can I do this in pure CSS? Do I need to listen to events and update the style? How? (Note: the font in this case is a one-liner, so this will probably make it easier, although I'm interested in a general solution).
source to share
You can add an event listener input
that will run whenever the value changes.
And in this listener, update input
size
.
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" />
source to share
A pure CSS solution that might help you:
you can fake input
using span
then do contenteditable="true"
which is widely supported see here
span {
border: 1px solid black;
display: inline-block;
white-space: nowrap;
}
<div>
<span contenteditable="true"> </span>
</div>
source to share