Lesson 21 of 55 · HTML
Styling Forms – Layout with Grid & Flexbox
Duration: 9 min
Form Layout Techniques
Flexbox example – simple label‑input pairs
<form class='flex-form'>
<label for='name'>Name</label><input id='name' type='text' />
<label for='email'>Email</label><input id='email' type='email' />
<button type='submit'>Send</button>
</form>
.flex-form {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.flex-form label { flex-basis: 100%; }
.flex-form input { flex: 1 1 200px; }
Flexbox keeps label‑input pairs on the same line on larger screens but wraps on mobile.
Grid example – more complex form
<form class='grid-form'>
<label for='msg'>Message</label>
<textarea id='msg'></textarea>
<button type='submit'>Submit</button>
</form>
.grid-form {
display: grid;
grid-template-columns: 1fr 2fr; /* label column, control column */
gap: 0.5rem;
}
.grid-form button { grid-column: 2; }
Grid makes it easy to line up labels and controls in a consistent column layout.
Accessibility notes
- Keep
<label>elements associated with inputs viafor/id. - Use
<fieldset>and<legend>to group related controls (e.g., address fields). - Ensure focus order follows visual order; avoid CSS that reorders elements without changing the DOM order.
- Provide error messages in a live region (
role='alert') so screen readers announce them immediately.
Quick checklist for form layout
- Labels correctly bound to inputs (
for/id)? ✅ - Layout container (
display:flexordisplay:grid) chosen appropriately? ✅ gapused for consistent spacing instead of margins? ✅<fieldset>/<legend>used for logical grouping? ✅- Live region for validation messages present? ✅
Tip: Combine Flexbox for simple rows and Grid for more complex two‑column forms to keep the markup lean.