CSS

Vertically Align Form Elements with Flexbox

Efficiently align labels and input fields in forms using CSS Flexbox `align-items` property, creating clean and structured form layouts with consistent spacing.

.form-group {
  display: flex;
  align-items: center; /* Vertically aligns items in the center */
  gap: 15px; /* Space between label and input */
  margin-bottom: 15px;
}

.form-group label {
  flex-shrink: 0; /* Prevent label from shrinking */
  width: 120px; /* Fixed width for labels */
  text-align: right;
  font-weight: bold;
}

.form-group input[type="text"],
.form-group input[type="email"] {
  flex-grow: 1; /* Allow input to fill remaining space */
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  max-width: 300px;
}

.form-container {
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  max-width: 600px;
  margin: 30px auto;
  background-color: #fff;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

/* Basic HTML structure for context */
/*
<div class="form-container">
  <form>
    <div class="form-group">
      <label for="name">Name:</label>
      <input type="text" id="name" name="name">
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" id="email" name="email">
    </div>
    <div class="form-group">
      <label for="message">Message:</label>
      <textarea id="message" name="message" rows="4"></textarea>
    </div>
  </form>
</div>
*/
How it works: This snippet provides a clean way to align form elements (labels and inputs) vertically using Flexbox. By setting `.form-group` to `display: flex` and `align-items: center`, the label and input are vertically centered relative to each other. `gap: 15px` provides consistent horizontal spacing. Giving the `label` a fixed `width` and the `input` `flex-grow: 1` ensures they distribute space effectively, creating an organized and user-friendly form layout.

Need help integrating this into your project?

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

Hire DigitalCodeLabs