This example illustrates the effect of field-sizing: content
on single- and multi-line text fields. The fields adjust their size as text is added or removed, effectively shrinkwrapping the contents, until a lower or upper size limit is reached.
HTML
The HTML in this example contains three form fields, each with an associated <label>
: two <input>
elements of types text
and email
and a <textarea>
element.
<div>
<label for="name">Enter name:</label>
<input type="text" id="name" maxlength="50" />
</div>
<div>
<label for="email">Enter email:</label>
<input type="email" id="email" maxlength="50" placeholder="e.g. a@b.com" />
</div>
<div>
<label for="comment">Enter comment:</label>
<textarea id="comment">This is a comment.</textarea>
</div>
Note the following points about the HTML:
- The first two fields have a
maxlength
attribute set, which stops the size of the field from increasing when the character limit is reached. - The
<textarea>
will grow in the inline direction until the edge of the min-width
constraint (set in the CSS code below) is reached, then start to add new lines in the block direction to contain subsequent characters. - The
email
input has a placeholder set. This causes the field to render big enough to show the entire placeholder. Once the field is focused and the user starts typing, the field changes size to the min-width
value. The text
field, which doesn't have a placeholder, renders initially at min-width
.
CSS
In the CSS, we set field-sizing: content
on the three form fields, along with a min-width
and max-width
to constrain the input size. It is worth reiterating that, if no minimum width was set on the fields, they would be rendered only as wide as the text cursor.
We also give the <label>
s some rudimentary styling so that they sit neatly next to the fields.
input,
textarea {
field-sizing: content;
min-width: 50px;
max-width: 350px;
}
label {
width: 150px;
margin-right: 20px;
text-align: right;
}
Result
Try entering and removing text in the fields below to explore the effects of field-sizing: content
alongside other sizing properties.