CSS

Responsive Form Layout with Aligned Labels using Flexbox

Create flexible and responsive form layouts where labels and inputs align perfectly on large screens and stack gracefully on smaller devices using CSS Flexbox for optimal usability.

.form-group {
  display: flex;
  flex-wrap: wrap; /* Allow items to wrap to the next line */
  align-items: center; /* Vertically align items */
  margin-bottom: 15px;
}

.form-group label {
  flex: 0 0 150px; /* Fixed width for label, no grow, no shrink */
  margin-right: 15px;
  text-align: right; /* Align label text to the right */
  padding-right: 10px;
}

.form-group input[type="text"],
.form-group input[type="email"],
.form-group select {
  flex: 1 1 200px; /* Allow input to grow/shrink, with a base width */
  padding: 8px 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  min-width: 0; /* Important for flex items */
}

/* Stack on small screens */
@media (max-width: 768px) {
  .form-group {
    flex-direction: column; /* Stack label and input vertically */
    align-items: flex-start; /* Align items to the start */
  }
  .form-group label {
    flex: 0 0 auto; /* Label takes auto width */
    width: 100%; /* Label takes full width */
    margin-right: 0;
    margin-bottom: 5px; /* Add space below label */
    text-align: left; /* Align label text to the left */
    padding-right: 0;
  }
  .form-group input[type="text"],
  .form-group input[type="email"],
  .form-group select {
    width: 100%; /* Input takes full width */
  }
}
How it works: This snippet uses Flexbox to create a responsive form layout. The `.form-group` acts as a flex container, aligning labels and inputs horizontally by default. `flex-wrap: wrap` allows items to stack on smaller screens. Labels are given a fixed `flex-basis` and `flex-shrink: 0`, while inputs are allowed to `flex-grow: 1` and have a `flex-basis`. A media query switches to `flex-direction: column` for smaller viewports, making labels and inputs stack vertically, ensuring readability and usability on mobile devices.

Need help integrating this into your project?

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

Hire DigitalCodeLabs