CSS
Aligning Form Labels and Inputs with Flexbox for Clean Layouts
Craft perfectly aligned form layouts using CSS Flexbox, ensuring labels and their corresponding input fields line up neatly, enhancing user experience and visual appeal.
.form-group {
display: flex;
flex-wrap: wrap; /* Allow wrapping on smaller screens */
align-items: center; /* Vertically align items */
margin-bottom: 15px;
gap: 10px; /* Space between label and input */
}
.form-group label {
flex: 0 0 120px; /* Fixed width for labels */
text-align: right;
padding-right: 15px;
font-weight: bold;
}
.form-group input[type="text"],
.form-group input[type="email"],
.form-group textarea {
flex: 1; /* Input takes remaining space */
min-width: 200px; /* Ensure input is not too small */
padding: 8px 12px;
border: 1px solid #ccc;
border-radius: 4px;
}
.form-group.full-width-input label {
flex: 1 1 100%; /* Label takes full width on top of input */
text-align: left;
padding-right: 0;
margin-bottom: 5px;
}
.form-group.full-width-input input,
.form-group.full-width-input textarea {
flex: 1 1 100%; /* Input takes full width */
}
@media (max-width: 600px) {
.form-group label {
flex: 1 1 100%; /* Labels stack above inputs on mobile */
text-align: left;
padding-right: 0;
margin-bottom: 5px;
}
.form-group input[type="text"],
.form-group input[type="email"],
.form-group textarea {
flex: 1 1 100%; /* Inputs take full width on mobile */
}
}
How it works: This Flexbox snippet streamlines form layouts by aligning labels and input fields. Each `.form-group` uses `display: flex` to place the label and input side-by-side. Labels are given a fixed width with `flex: 0 0 120px` and text-aligned right, while inputs `flex: 1` to fill the remaining space. Media queries ensure a responsive stack for labels and inputs on smaller screens, enhancing usability and readability across devices.