CSS Grid and forms.

Have I already said how much I adore CSS Grid? We have a really potent layout tool at our disposal.

Grids can be made without adding a lot of wrapping html elements (divitis).

Example: Form Grid

So lets show an example of how I used CSS grid to create a layout for a simple form.

As you can see, this is a pretty decent method for building a form and gridding the fields.

<style>
.form-grid {
border: 1px solid var(--error-color);
display: grid;
grid-template-columns: repeat(12, 1fr);
column-gap: 18px;
row-gap: 38px;
}
.form-grid > div input {
width: 100%;
}
</style>
<form class="form-grid">
<div style="grid-column: span 6">
<label for="l1">Label</label>
<input id="l1" type="text" value="Value 1 grid-span 6">
</div>
<div style="grid-column: span 6">
<label for="l2">Label</label>
<input id="l2" type="text" value="Value 2 grid-span 6">
</div>
<div style="grid-column: span 3">
<label for="l3">Label</label>
<input id="l3" type="text" value="Value 3 grid-span 3">
</div>
<div style="grid-column: span 9">
<label for="l9">Label</label>
<input id="l9" type="text" value="Value 4 grid-span 9">
</div>
</form>

Example: Form Field Grid

Consequently, a suitable form field comprises the following components.

  1. Input
  2. Label
  3. Description
  4. Errors

Let's assume that this appears as follows:

<style>
/*...*/
/* The previous CSS is still active for the form grid ofc :) */
.form-field {
display: grid;
/*Here I create template areas, each is a new 'line' or 'row'. */
grid-template-areas: "label" "input" "error" "description";

/* Then I set each row to 0fr, which tricks the browser to shrink just enough that everything sits and fits :) */
/* One entry for each row (4 times 0fr) */
grid-template-rows: 0fr 0fr 0fr 0fr;
}
/* Now we assign each element inside the .form-field wrapper the proper areas. */
label { grid-area: label; }
input { grid-area: input; }
.description { grid-area: description; }
.error { grid-area: error; color: var(--error-color); }
</style>
<form class="form-grid">
<div class="form-field" style="grid-column: span 6">
<label for="l1">Label</label>
<input id="l1" type="text" value="Value 1 grid-span 6">
<span class="description">Make sure you input something here</span>
<span class="error">This error is visiblle as to see how this works.</span>
</div>
<div style="grid-column: span 6">
<label for="l2">Label</label>
<input id="l2" type="text" value="Value 2 grid-span 6">
<span class="description">This is another description.</span>
<span class="error" hidden>This error is not visible as to see how this works.</span>
</div>
</form>
Make sure you input something here This error is visiblle as to see how this works.
This is another description.

So if you play with the grid-template-areas in the inspector you can shuffle items around.

Powerful right?