A textarea that grows as you type
Caveatfield-sizing: content lets a textarea grow with what is typed, with no JavaScript. Cap it with max-height, or a long paste pushes the submit button off screen, which is worse than the scrollbar you were removing. lh units keep the bounds in lines instead of guessed pixels.
FallbackChromium has had it since 123, Safari since 26.2 and Firefox since 152. An older browser ignores the property and shows a plain textarea at whatever rows says, so set rows to the height you would have shipped anyway. If those browsers still matter, the few lines of script under the CSS resize the box from scrollHeight and only run where the property is missing.
<textarea rows="2"></textarea>
textarea {
field-sizing: content;
min-height: 3lh;
/* or it eats the page */
max-height: 9lh;
resize: none;
}
// only for browsers without field-sizing
if (!CSS.supports("field-sizing: content")) {
addEventListener("input", e => {
const t = e.target;
if (t.localName !== "textarea") return;
t.style.height = "auto";
const edge = t.offsetHeight - t.clientHeight;
t.style.height = t.scrollHeight + edge + "px";
});
}
Published