Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make <input> (and enclosing <div>) automatically as wide as content

Tags:

html

css

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).

like image 779
0__ Avatar asked Jan 07 '23 22:01

0__


2 Answers

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">&nbsp;</span>
like image 149
dippas Avatar answered Mar 08 '23 15:03

dippas


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" />
like image 22
Oriol Avatar answered Mar 08 '23 15:03

Oriol