CSS: Grid

Jonathan Wong
3 min readSep 20, 2020

What is CSS Grid? Remember my last post about CSS flexbox? Well, similar to flexbox, CSS grid is a tool used for laying out several elements in applications. As the name suggests, it provides a grid-based layout. What makes CSS grid different from flexbox, is that the CSS grid has rows and columns, making it two dimensional.

As the image above shows, flexbox works for just aligning items horizontally, while CSS grid works for aligning items horizontally and vertically.

So how does it work? Similar to flexbox, it contains a parent element or container and the children elements and items.

<div class=”grid-example-container”>
<div class=”grid-example-item”>1</div>
<div class=”grid-example-item”>2</div>
<div class=”grid-example-item”>3</div>
<div class=”grid-example-item”>4</div>
<div class=”grid-example-item”>5</div>
<div class=”grid-example-item”>6</div>
<div class=”grid-example-item”>7</div>
<div class=”grid-example-item”>8</div>
<div class=”grid-example-item”>9</div>
</div>

In this context, grid-example-container is the parent element and the grid-example-items are the items.

The bare necessities required to create a CSS grid are

display: grid and grid-template-columns: auto auto auto on the parent element.

However, you’re better than that!

.grid-example {
display: grid;
grid-template-columns: auto auto auto;
padding: 10px;
}
.grid-example-item {
font-size: 30px;
padding: 20px;
text-align: center;
border-style: solid;
}

The CSS code above would provide the grid below.

The possibilities are limitless in terms how you want to stylize the grid.

You can also apply gaps in between the rows and columns. Say for instance, you wanted to put a gap between columns. You could just add grid-column-gap to the container. Look at the example below.

.grid-example {
display: grid;
grid-template-columns: auto auto auto;
padding: 10px;
grid-column-gap: 10px;
}

The same goes for putting a gap between rows. Instead of adding grid-column-gap, you’d just put grid-row-gap.

You could use the shorthand method if you wanted to change both by using grid-gap. For example grid-gap: 10px 30px, in which the first number would refer to the row gap and the second number would be referencing the column gap.

.grid-example {
display: grid;
grid-template-columns: auto auto auto;
padding: 10px;
grid-gap: 10px 30px;
}

The code above would create the grid you see in the image below.

Conclusion

In summation, grid is a great way for displaying several elements and allows for more flexibility than flexbox because it allows developers to change the rows and columns. Check out the links below for more information!

--

--