CSS, HTML
Responsive Stacked Form with Flexbox
Build a flexible and responsive form layout using CSS Flexbox, where labels and input fields stack vertically and adjust gracefully to different screen sizes for improved user experience.
<form class="flex-form">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter your email">
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea id="message" rows="4" placeholder="Your message"></textarea>
</div>
<div class="form-group form-group--buttons">
<button type="submit">Submit</button>
<button type="reset">Clear</button>
</div>
</form>
.flex-form {
display: flex;
flex-direction: column; /* Stack form groups vertically */
gap: 1rem; /* Spacing between form groups */
max-width: 500px;
margin: 2rem auto;
padding: 1.5rem;
border: 1px solid #ccc;
border-radius: 8px;
background-color: #f9f9f9;
}
.form-group {
display: flex;
flex-direction: column; /* Stack label and input within group */
gap: 0.5rem; /* Spacing between label and input */
}
.form-group label {
font-weight: bold;
color: #555;
}
.form-group input,
.form-group textarea {
padding: 0.75rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
width: 100%; /* Make inputs take full width of their container */
}
.form-group--buttons {
flex-direction: row; /* Buttons can be side-by-side */
justify-content: flex-end; /* Align buttons to the right */
gap: 0.75rem;
}
.form-group--buttons button {
padding: 0.75rem 1.5rem;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: bold;
}
.form-group--buttons button[type="submit"] {
background-color: #007bff;
color: white;
}
.form-group--buttons button[type="reset"] {
background-color: #6c757d;
color: white;
}
How it works: This snippet illustrates how to create a responsive stacked form layout using CSS Flexbox. The main form container uses `flex-direction: column` to stack `form-group` elements. Each `form-group` also uses `flex-direction: column` to stack its label and input. This approach ensures form fields maintain a clear vertical alignment and adapt well to various screen sizes, with specific styling for buttons to align them horizontally.