CSS

CSS Flexbox: Aligning Form Labels and Inputs

Master responsive form layouts using CSS Flexbox to perfectly align labels with their input fields, creating clean and user-friendly forms with consistent spacing and alignment.

.form-group {
  display: flex;
  flex-direction: column; /* Stack label and input vertically */
  margin-bottom: 15px;
}

.form-group label {
  margin-bottom: 5px;
  font-weight: bold;
  color: #333;
}

.form-group input[type="text"],
.form-group input[type="email"],
.form-group textarea {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1em;
}

/* Alternative layout: labels and inputs side-by-side */
.form-row {
  display: flex;
  align-items: center; /* Vertically align label and input */
  margin-bottom: 15px;
}

.form-row label {
  flex: 0 0 120px; /* Fixed width for labels */
  margin-right: 15px;
  font-weight: bold;
  color: #333;
}

.form-row input[type="text"],
.form-row input[type="email"] {
  flex: 1; /* Input takes remaining space */
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1em;
}
How it works: This snippet showcases two common Flexbox patterns for form layouts. The first, `.form-group`, uses `flex-direction: column` to stack labels and inputs vertically, suitable for simpler forms or mobile-first designs. The second, `.form-row`, demonstrates how to align labels and inputs horizontally side-by-side. By giving the label a fixed `flex-basis` (e.g., `flex: 0 0 120px`) and the input `flex: 1`, labels maintain a consistent width while inputs automatically fill the remaining space, ensuring clean alignment across different form fields.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs