← Back to all snippets
CSS

Flexbox: Distribute Space and Align Form Elements

Efficiently layout form labels and input fields side-by-side using Flexbox, achieving consistent alignment and smart space distribution for improved UI design and readability.

<form class="flex-form">
  <div class="form-group">
    <label for="name">Name:</label>
    <input type="text" id="name" placeholder="Your Name">
  </div>
  <div class="form-group">
    <label for="email">Email:</label>
    <input type="email" id="email" placeholder="Your Email">
  </div>
  <div class="form-group">
    <label for="message">Message:</label>
    <textarea id="message" rows="3" placeholder="Your Message"></textarea>
  </div>
  <button type="submit">Send</button>
</form>

.flex-form {
  display: flex;
  flex-direction: column;
  gap: 15px; /* Spacing between form groups */
  max-width: 400px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.form-group {
  display: flex;
  flex-direction: column; /* Stack label and input */
}

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

.form-group input,
.form-group textarea {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 100%; /* Make inputs fill available width */
}

/* Optional: For horizontal label-input alignment */
/* .form-group.horizontal {
  flex-direction: row;
  align-items: baseline;
  gap: 10px;
}
.form-group.horizontal label {
  flex-shrink: 0; 
  width: 80px;
  text-align: right;
}
.form-group.horizontal input,
.form-group.horizontal textarea {
  flex-grow: 1;
} */

button[type="submit"] {
  padding: 10px 15px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  align-self: flex-start; /* Align button to start */
}

button[type="submit"]:hover {
  background-color: #0056b3;
}
How it works: This snippet uses Flexbox to structure a simple form. The main form container is a flex column with `gap` for spacing between form groups. Each `.form-group` is also a flex column, stacking its label and input. The commented-out section shows how to adapt a `.form-group` to arrange labels and inputs horizontally, demonstrating `flex-direction: row`, `align-items`, and `flex-grow` to manage space for a more complex layout, useful for responsive form designs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs