CSS Grid Introduction

mcardona9015

mcardona9015

Posted on March 11, 2021

CSS Grid Introduction

CSS GRID

There are many ways to style your website, and today I'm going to give a brief introduction to styling using CSS Grid layout. CSS grid provides you with a modular and dynamic way to layout your website. We'll start with a simple 3 x 3 grid example.

Codepen Example

Getting started with display: grid;

The first thing you need to do to get started with CSS grid is to select the element you would like to turn into a grid and give it a display property of display: grid;. This will be the parent element, which you can think of as the outer container of the grid. All of its child elements can then be placed in the columns and rows you define within the grid.

grid-template-columns and grid-template-rows

The next step is to define how many rows and column you would like to give your grid and what size they should be. A common choice for size is to use fr, a fractional unit which represents a fraction of the available space in the grid container.

For the columns we will give the container a property of grid-template-columns and then specify the size of the column using fr. A column will be created for each size declared. If we wanted three columns, with the middle column taking up half the space, we would set the property as grid-template-columns: 1fr 2fr 1fr;.

We can specify the rows in a similar fashion using grid-template-rows. If we wanted three identically sized rows we could specify the row size to repeat three times at the size of 1fr using repeat() notation like so: grid-template-rows: repeat(3, 1fr);

grid-column and grid-row

Now that we have our grid container set up we can place its child elements anywhere we specify in the grid using the grid-column and grid-row properties.

In our 3 x 3 grid example if we wanted to place a specific child element in the center of the grid at column two - row two we would select the element in our css and give it properties of:
grid-row: 2;
grid-column: 2;

Grids within grids

Child elements of grids can also be grids themselves. It is possible to have multiple layers of grids, each with their own specific column and row sizes. Another use case for giving child elements the display: grid; property is to gain access to the place-items property. This is a handy shortcut for aligning and justifying an elements content in one line. using
place-items: center;
will center any items within that grid.

Wrap-up

There are many, many other use cases and properties for CSS Grid Layout, but if you know the basics laid out above then you are on your way to creating orderly, dynamic websites! You can checkout more about CSS Grid at the MDN docs here.

💖 💪 🙅 🚩
mcardona9015
mcardona9015

Posted on March 11, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

CSS Grid Introduction
css CSS Grid Introduction

March 11, 2021