Grid for Forms

Excerpt

Another grid but the most comprehensive one.

Building grids with CSS is a long ongoing story from using tables 20 years ago until the display:grid was implemented in CSS as we know it today. Again the technology was not really in focus for building web applications as IE11 was used by many users and many features did work different there.

Thanks to Microsoft they RIPed IE finally after long time driving the web technology (remembering the outstanding IE5).

Thanks to Microsoft they RIPed it.

Building a grid for forms

We like things to be aligned like the labels and inputs in the form showcase below. This can be achieved by many css-grid-vs-flexbox-which-layout-to-choose-and-why like

After trying all of the above in the last decades I must consist that the grid version is the most compact one.

Form example

Grid is the real Grid

To define a grid only the container element must be styled (in contrast to the flex element):

.formgrid { display: grid; grid-template-columns: 1fr 2fr 1fr; }

Of course there is more like gaps, repeat minmax functions etc. that help implementing a responsive grid.

Grid layout for data forms

I found is is usable for form layouts as well so here is the core implementation of a grid where labels are in column 1 and column 2 is used for the input elements.

.formgrid {
  display: grid;
  grid-template-columns: 16ch auto;
  grid-column-gap: .4em;
  grid-row-gap: .2em;
}

With 2 additional rules the labels are always placed into the first column while all other elements will go to the last column.

.formgrid>* {
  grid-column-end: -1;
}

.formgrid>label {
  grid-column: 1;
}

The grid can be shrinked to a 1 column when the horizontal place is small by using a media rule:

@media (max-width: 767px) {
  .formgrid {
    grid-template-columns: auto;
  }

  .formgrid>label {
    text-align: left;
  }
}

Comments

The grid is quiet usefull and well designed. I like that with minimal CSS a realistic usable grid can be built. Definitively a feature to be used.

See also

Tags

CSS