CSS

Aligning Form Labels and Inputs with CSS Grid

Create perfectly aligned and responsive form layouts using CSS Grid. This snippet demonstrates structuring labels and input fields for improved readability and user experience.

.form-container {
  display: grid;
  /* Defines two columns: one for labels (auto width) and one for inputs (1fr for remaining space) */
  grid-template-columns: auto 1fr;
  gap: 15px 25px; /* Vertical gap, Horizontal gap */
  max-width: 600px;
  margin: 2rem auto;
  padding: 2rem;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: #fff;
}

.form-container label {
  grid-column: 1 / 2; /* Ensures labels are in the first column */
  text-align: right; /* Align labels to the right */
  padding-top: 5px; /* Align with input text vertically */
  font-weight: bold;
  color: #333;
}

.form-container input[type="text"],
.form-container input[type="email"],
.form-container textarea {
  grid-column: 2 / 3; /* Ensures inputs are in the second column */
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box; /* Include padding and border in the element's total width and height */
}

.form-container .form-submit {
  grid-column: 1 / 3; /* Button spans both columns */
  text-align: center;
  margin-top: 1rem;
}

.form-container button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1em;
}

.form-container button:hover {
  background-color: #0056b3;
}
How it works: This snippet uses CSS Grid to create a clean and aligned form layout. The `.form-container` is set to `display: grid` with `grid-template-columns: auto 1fr`. This creates two columns: the first (`auto`) adapts to the width of the longest label, and the second (`1fr`) takes up the remaining space for the input fields. `gap` provides consistent spacing. Labels are explicitly placed in the first column with `grid-column: 1 / 2` and aligned `text-align: right`, while input fields are in the second column with `grid-column: 2 / 3`. A submit button can span both columns using `grid-column: 1 / 3`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs