Sub topic 3
Aligning Form Labels and Controls Across Fields
Assume you know CSS selectors, the box model, and basic Grid placement. This chapter uses grid-column, gap, subgrid, and line names.
Aligning Form Labels and Controls Across Fields
A nested grid normally creates its own tracks. That means each field could calculate a different label-column width. Use subgrid so every field inherits the parent form’s columns.
<form class="settings-form">
<div class="field">
<label for="name">Name</label>
<input id="name" type="text">
</div>
<div class="field">
<label for="email">Email address</label>
<input id="email" type="email">
</div>
</form>.settings-form {
display: grid;
grid-template-columns: max-content minmax(12rem, 1fr);
gap: 0.75rem 1rem;
max-width: 32rem;
}
.field {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
align-items: center;
}
.field input {
min-width: 0;
}Each .field spans both parent columns. Its subgrid then reuses the parent’s label and control tracks. Therefore, all labels share one width, and all controls start at the same position.
Fallbacks with `@supports`
Browsers without subgrid can use explicit columns. Feature detection applies the enhanced layout only when supported.
.field {
display: grid;
grid-template-columns: max-content 1fr;
gap: 0.75rem 1rem;
}
@supports (grid-template-columns: subgrid) {
.field {
grid-column: 1 / -1;
grid-template-columns: subgrid;
}
}The fallback keeps each field usable, although label widths may differ.
Line Names in Subgrids
You can name inherited lines and place children by name:
.settings-form {
grid-template-columns: [label-start] max-content [control-start] 1fr [control-end];
}
.field {
grid-column: 1 / -1;
grid-template-columns: subgrid;
}
.field input {
grid-column: control-start / control-end;
}Track Sizing and Common Pitfalls
Content in a subgrid can contribute to the parent’s track sizing. A long label may widen the parent’s max-content label column. This is useful, but unexpected text can make the form wider than planned.
Remember these limits:
subgridinherits tracks in one axis at a time. Use it for columns, rows, or both.- The subgrid must span the parent tracks it needs.
- A subgrid cannot invent extra inherited tracks.
gapis inherited for the subgridded axis, but you can override it locally.- Check the fallback in browsers that lack
subgrid.
Exercise
Why does .field need grid-column: 1 / -1 in the form example?
Show answer
It must span the parent’s label and control tracks before its subgrid can inherit both tracks.