<h1>Auto Expand Input Height based on Text Length</h1>
<h2>Inputs</h2>
<p><strong>Problem (doesn't resize horizontally):</strong>
<input class="input" value="99" type="number"></p>
<p><strong>Solution with span:</strong><span class="input" role="textbox" contenteditable>99</span></p>
<p><strong>Solution with JS:</strong><span class="input-wrap"><span class="width-machine" aria-hidden="true">99</span><input class="input" value="99" type="number"></span></p>
.input {
border: 1px solid #ccc;
font-family: inherit;
font-size: inherit;
padding: 1px 6px;
}
.input-wrap {
position: relative;
}
.input-wrap .input {
position: absolute;
width: 100%;
left: 0;
}
.width-machine {
/* Sort of a magic number to add extra space for number spinner */
padding: 0 1rem;
}
/* Just for demo */
* {
box-sizing: border-box;
}
body {
font-family: "Heebo", sans-serif;
max-width: 500px;
margin: 0 auto;
padding: 1rem;
}
p strong {
display: block;
}
h1 {
border-bottom: 5px solid blue;
}
h2 {
border-bottom: 2px solid navy;
}
// Dealing with Input width
let el = document.querySelector(".input-wrap .input");
let widthMachine = document.querySelector(".input-wrap .width-machine");
el.addEventListener("keyup", () => {
widthMachine.innerHTML = el.value;
});
// Dealing with Textarea Height
function calcHeight(value) {
let numberOfLineBreaks = (value.match(/\n/g) || []).length;
// min-height + lines x line-height + padding + border
let newHeight = 20 + numberOfLineBreaks * 20 + 12 + 2;
return newHeight;
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.