CSS
Structuring Accessible and Responsive Form Layouts with CSS Grid
Organize form labels and inputs into a clean, accessible, and responsive grid, simplifying complex form designs and improving user experience.
.form-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); /* Responsive columns */
gap: 1.5rem; /* Spacing between form groups */
padding: 1rem;
max-width: 900px;
margin: 2rem auto;
background-color: #f9f9f9;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.form-group {
display: flex;
flex-direction: column;
}
.form-group label {
margin-bottom: 0.5rem;
font-weight: bold;
color: #333;
}
.form-group input,
.form-group textarea,
.form-group select {
padding: 0.8rem;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
}
.form-grid .full-width {
grid-column: 1 / -1; /* Make an item span all columns */
}
.form-grid button {
grid-column: 1 / -1; /* Button spans all columns */
padding: 1rem 1.5rem;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 1.1rem;
transition: background-color 0.3s ease;
}
.form-grid button:hover {
background-color: #0056b3;
}
How it works: This snippet utilizes CSS Grid to create a responsive and well-structured form layout. The `.form-grid` container uses `grid-template-columns: repeat(auto-fit, minmax(280px, 1fr))` to automatically create columns that fit within the available space, collapsing into a single column on smaller screens. `gap` provides spacing between form fields. Specific classes like `.full-width` allow elements to span across all grid columns, useful for longer input fields or submission buttons.