CSS

Dynamic Form Layout with Aligned Labels using Flexbox

Create responsive and visually appealing form layouts where labels and input fields align perfectly using Flexbox, adapting to different screen sizes.

.form-group {
  display: flex;
  flex-wrap: wrap;
  align-items: center; /* Vertically align items */
  gap: 10px; /* Space between label/input and other form groups */
  margin-bottom: 15px;
}

.form-group label {
  flex-basis: 150px; /* Fixed width for labels */
  flex-shrink: 0; /* Prevent label from shrinking */
  text-align: right; /* Align label text to the right */
  padding-right: 10px;
}

.form-group input,
.form-group select,
.form-group textarea {
  flex-grow: 1; /* Input field takes remaining space */
  min-width: 200px; /* Ensure input is not too small on wrap */
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

/* Optional: Styles for when items wrap */
@media (max-width: 600px) {
  .form-group label {
    flex-basis: 100%; /* Labels take full width on small screens */
    text-align: left;
    padding-right: 0;
  }
}
How it works: This snippet demonstrates how to create flexible form layouts where labels and input fields are aligned. By setting `display: flex` on the `.form-group`, labels are given a fixed `flex-basis` and prevented from shrinking. Input fields use `flex-grow: 1` to occupy the remaining horizontal space. `flex-wrap: wrap` ensures the layout adapts gracefully to smaller screens, with labels potentially stacking above inputs due to the media query. `gap` provides consistent spacing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs