Style Forms With CSS Subgrids
As you can see, this is an ugly looking form in so many aspects, but here I want to highlight the part where there are no equal spacing between the labels and the inputs.
Basically, I want my form to look like this:
One workaround is that you can make each row a flex-box container and then give a gap by estimating the largest possible text in the label. This involves hit-and-trial method where you put an arbitrary number and hope that it spaces out evenly. However, the next time we add another field to this form with a long label text. We might again need to change the gap between them. It involves re-tweaking the styles.
A more elegant solution would be to do this with CSS Subgrids.
A subgrid in CSS is a type of grid layout that allows a nested grid (a grid inside another grid) to inherit and share the same row or column lines from its parent grid. This makes it easier to align and organize the content of the nested grid based on the structure of the outer grid, creating a consistent and seamless layout without needing to define separate grid lines for the inner content. It helps maintain alignment and order across both the parent and nested grids.
The code to obtain the desired styling is as follows:
<div class="form-control">
<div class="form-item">
<label for="first_name">First Name:</label>
<input type="text" name="first_name" />
</div>
<div class="form-item">
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" />
</div>
<div class="form-item">
<label for="email">Email:</label>
<input type="email" name="email" />
</div>
<div class="form-item">
<label for="password">Password:</label>
<input type="password" name="password" />
</div>
</div>
.form-control {
max-width: 350px;
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 0.5rem;
}
.form-item {
grid-column: span 2;
display: grid;
grid-template-columns: subgrid;
}
Codepen link:
Subscribe to my newsletter
Read articles from Rasil Maharjan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by