Creating a simple form with CSS Grid


You learned to create a simple form with Flexbox in the previous article. Today, you’ll understand how to create the same thing with CSS Grid.

Here’s what we’re building:

The simple form we're building consists of one email input and one submit button

Building the form with CSS Grid

From the picture above, we know the form contains two elements:

  1. An email field
  2. A submit button

Here’s the HTML:

  <input type="email" name="email" />
  <button type="submit">Send</button>

To build the form with CSS Grid, you need to set the parent’s display property to grid.

form {
  display: grid;

Here’s what you get:

Two rows of elements. The first row is the email input. The second row is the submit button

Why did we get two rows?

We get two rows because we did not specify the number of columns for the grid. Browsers will always default to one column.

For this form, we need to set two columns.

  1. The first column should expand to fill up any available space
  2. The second column should be sized according to its contents

For the first column, we can use the fr unit. For the second column, we can use auto.

form {
  display: grid;
  grid-template-columns: 1fr auto;

With this, you have completed form’s layout. Here’s a Codepen for you to play:

See the Pen Simple form with CSS Gridby Zell Liew (@zellwk) onCodePen.

When elements are of unequal height…

We will simulate elements of unequal height by substituting the button’s text with an SVG. This is the same as what we’ve done in the previous article.

<form action="#">
  <input type="email" placeholder="Enter your email" />
  <button type="button">
    <svg><!-- a smiley icon --></svg>
Adding a smiley icon as the to the submit button

Notice the input’s height increases to fit the large SVG icon too! Once again, we don’t have to write any extra code. This happens because grid items are stretched vertically to fill up any available space.

If you want to change this behavior, you can change the align-items property to either start, end, or center.

Items can be aligned differently if you set `align-items` to a different value

Here’s a Codepen for you to play:

See the Pen Simple form with CSS Grid (with SVG Button)by Zell Liew (@zellwk) onCodePen.

Wrapping up

CSS Grid makes it easy to create layouts. It doesn’t have to be used for macro layout. It can also be used for micro layouts like the form example you’ve seen here.

Have fun with CSS Grid!

Can I send you a few articles that will help you become amazing at CSS?

Learn the fundamentals that will help you build as strong foundation so you never get confused.