CSS
CSS Grid for Structured Form Field Alignment
Create well-aligned and accessible form layouts using CSS Grid, ensuring labels and input fields line up perfectly across multiple columns for improved UX.
.form-grid {
display: grid;
grid-template-columns: auto 1fr; /* Label takes content width, input takes rest */
gap: 10px 20px; /* Row gap, Column gap */
align-items: center; /* Vertically align labels and inputs */
}
.form-grid label {
text-align: right;
padding-right: 10px;
}
.form-grid .full-width {
grid-column: 1 / -1; /* Spans across all columns */
}
How it works: This CSS Grid snippet creates a structured and aligned layout for form elements. `grid-template-columns: auto 1fr` ensures labels take only the necessary width, while input fields fill the remaining space. `gap` provides consistent spacing, and `align-items: center` vertically aligns labels with their corresponding inputs. The `.full-width` class demonstrates how to make an element span across all defined columns, useful for messages or full-width buttons.