CSS
Aligned Form Layout with CSS Grid
Structure complex forms with perfectly aligned labels, input fields, and action buttons using CSS Grid for a clean, readable, and consistent user interface.
.form-grid {
display: grid;
grid-template-columns: auto 1fr; /* Auto-width for labels, 1fr for inputs */
gap: 15px 10px; /* Row gap, column gap */
max-width: 600px;
margin: 20px auto;
padding: 20px;
border: 1px solid #eee;
border-radius: 8px;
background-color: #f9f9f9;
}
.form-grid label {
text-align: right; /* Align labels to the right */
padding-right: 10px;
align-self: center; /* Vertically center labels with inputs */
}
.form-grid input,
.form-grid select,
.form-grid textarea {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
.form-actions {
grid-column: 1 / -1; /* Span across all columns */
text-align: right;
padding-top: 10px;
}
.form-actions button {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
/* Adjust for single column on small screens */
@media (max-width: 600px) {
.form-grid {
grid-template-columns: 1fr; /* Single column layout */
}
.form-grid label {
text-align: left; /* Labels align left in single column */
padding-right: 0;
}
.form-actions {
grid-column: 1; /* Reset to single column */
}
}
How it works: This snippet uses CSS Grid to create a well-aligned and responsive form layout. `grid-template-columns: auto 1fr` creates two columns: one for labels (auto-width based on content) and one for input fields (takes up remaining space). Labels are right-aligned and vertically centered using `align-self: center`. Action buttons are made to span all columns using `grid-column: 1 / -1`. A media query ensures the form stacks into a single column on smaller screens for better mobile usability, adapting the label alignment accordingly.