Ronalds Vilciņš

Let Form Controls Size Themselves With field-sizing

Making a <textarea> grow with its content has traditionally meant measuring it with JavaScript. field-sizing: content gives CSS a direct way to do it.

CSS
textarea,
select,
input {
  field-sizing: content;
}

The browser sizes each control from its content rather than keeping its usual fixed size. It can apply to text inputs, number inputs, file inputs, textareas, selects, and related controls, though the exact result depends on the control.

Type to let the fields grow
View code
HTML
<label for="title">Title</label><input id="title" type="text" value="A short title">
<label for="notes">Notes</label><textarea id="notes" rows="2">Add a few lines here.
The field can grow with its content.</textarea>
<p class="note">Try a longer title or several lines of notes. Unsupported browsers keep ordinary field sizing.</p>
CSS
button, select { padding: .35rem .6rem; border: 1px solid var(--clg); background: var(--cw); color: var(--cb); }
input[type="range"] { width: min(100%, 18rem); vertical-align: middle; }
h2, h3 { font-size: 1rem; }
.note { color: var(--clg); }

label { display: block; margin: .75rem 0 .3rem; }
input, textarea { field-sizing: content; max-inline-size: 100%; padding: .5rem; border: 1px solid var(--clg); background: var(--cw); color: var(--cb); }
input { min-inline-size: 12ch; }
textarea { display: block; inline-size: 100%; min-block-size: 3lh; max-block-size: 8lh; }

Do not forget the limits

An input that grows forever is technically responsive and practically awkward. Add minimum and maximum sizes that fit the layout:

CSS
textarea {
  field-sizing: content;
  min-block-size: 4lh;
  max-block-size: 12lh;
  max-inline-size: 100%;
}

The default value is fixed, which keeps the familiar control sizing. Because field-sizing was still a new feature when this article was written, check current browser support before relying on it without a fallback. The Chrome platform status page tracks the original implementation.

For a small progressive enhancement, this is a nice property. Keep the control usable without it, add sensible limits, and let supporting browsers remove a bit of JavaScript.

Filed under on

Last updated on

← Back to all articles