Create your account

Already have an account? Login here

Note: By joining, you will receive periodic emails from Coursetro. You can unsubscribe from these emails.

Create account

The Ultimate CSS Grid Positioning Tutorial

By Gary simon - Jan 18, 2018

At the time of writing this tutorial, the CSS Grid is supported by 76% of the browsers out there, and support is only going to increase from here on.

The CSS Grid allows you to quickly and easily position and align your content with breeze. Before the CSS grid, you had to integrate a bunch of annoying hacks to accomplish seemingly simple aligning and positioning goals.

Let's get started!

We have some pretty awesome courses

Check them out

If you prefer watching a video..

Be sure to Subscribe to the Official Coursetro Youtube Channel for more videos.

Getting our Playground Project Up and Running

While we are only going to be working with strictly HTML and CSS, I want to at least integrate live browser reloading with Gulp and browser-sync. This will make my life easier as a teacher. Plus, should you want to extend the Gulp file to accept sass or do other nifty things, you can do so.. 

First, you will need to Node.js for this part (Install them at Nodejs.org if you don't have them already).

Create a new project folder and hop into it:

> mkdir css-align && cd css-align

Create a package.json file to hold project dependencies:

> npm init -y

Use NPM to install Gulp and Browser-sync:

> npm install gulp browser-sync --save-dev

Next, we'll open up Visual Studio Code (I will, at least) by typing the following in the project folder:

> code .

Create an index.html file in the project folder with the following contents. (Note, you can type ! in VSC and hit enter, this will give you the following boilerplate HTML):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CSS Grid Alignment Playground</title>
    <link rel="stylesheet" href="css/main.css">
</head>
<body>

</body>
</html>

Notice I also added a reference to css/main.css.

So, create a css folder and an empty main.css file inside of it.

Next, create a file named gulpfile.js in the project folder and paste the following contents:

var gulp    = require('gulp');
var browserSync = require('browser-sync').create();

gulp.task('sync', function() {

    browserSync.init({
        server: {
            baseDir: "./"
        }
    });

    gulp.watch(["./*.html", "./css/*.css"]).on('change', browserSync.reload);
})

This will reload our browser for us automatically any time any HTML or CSS file is saved.

Finally, run gulp sync in the command line within the project folder:

> gulp sync

This will launch a browser at http://localhost:3000 with the project. We're ready to go now!

Horizontal and Vertical Centering with the CSS Grid

Let's make things simple with our HTML and define a single container that we want to position both horizontally and vertically:

<body>
    <div class="container">
        <h1>My Content</h1>
        <p>My paragraph content right here.</p>
    </div>
</body>

Our body tag is going to serve as the actual grid container, and the child element .container is what we will center horizontally and vertically.

In the main.css file, add:

body, html {
    margin: 0;
    height: 100%;
    font-family: 'Arial';
}

body {
    display: grid;
    grid-template-rows: auto;
    justify-items: center;
    align-items: center;
}

.container {
    grid-column-start: 1;

    background: rgb(230, 230, 230);
    border-radius: 10px;
    padding: 1em;
}

So, what's happening here?  

First, we're making the body element the grid container with display: grid; Next, we only have 1 row of content, so we set grid-template-rows to auto

The next two properties is what makes all of centering magic happen:

  • justify-items - This property asserts that all of the grid items (#container is our one and only grid item) should be aligned on the row axis based on the given value. In our case, it's center.
  • align-items - This property is the same as justify-items, except it's based on aligning via the column axis.

The result in your browser should look like this:

 

Try resizing your browser and you will see that it stays absolutely positioned in the center on both axises!

Centering Multiple Items

We just centered a single grid item, let's try adding 2 more to demonstrate some additional concepts.

Update your HTML so that it looks like this:

    <div class="container" id="item1">
        <h1>My Content</h1>
        <p>My paragraph content right here.</p>
    </div>
    <div class="container" id="item2">
        <h1>My Content 2</h1>
        <p>My paragraph content right here.</p>
    </div>
    <div class="container" id="item3">
        <h1>My Content 3</h1>
        <p>My paragraph content right here.</p>
    </div>

The result in the browser will look like this:

Instead of columns, how would we align these each other all on the same row?

Update your CSS to the following:

body {
    margin: 0;

    display: grid;
    grid-template-rows: auto;
    grid-template-columns: repeat(3, auto);
    grid-template-areas:
        "item1 item2 item3";

    justify-items: center;
    align-items: center;
}

Here, we've added grid-template-columns and used the repeat() function to create 3 columns, all with the value of auto.

I've also added grid-template-areas which allows us to structure both rows (in our case, 1 row with 3 columns) and give each grid area a name.

This name (item1 2 and 3) can then be referenced in the child elements, but we'll get to that in a second.

If you check out your browser, it should now look like this:

Awesome!

Aligning Single Items

So far, we have used the justify-items and align-items properties to handle the alignment of all grid items within our grid container.

But what if we only wanted to control the alignment of individual grid items?

Simple!

Let's try aligning each of our three grid items in a unique manner. First, we remove the justify-items and align-items properties from our grid container:

body {
    margin: 0;

    display: grid;
    grid-template-rows: auto;
    grid-template-columns: repeat(3, auto);
    grid-template-areas:
        "item1 item2 item3";
}

Next, we will use justify-self and align-self on each of the child containers. We will also use the grid-area property to match them with the grid-template-areas we defined in the parent container:

#item1 {
    grid-area: item1;
    justify-self: end;     /* Aligns to the right */
    align-self: start;     /* Aligns to the top   */
}

#item2 {
    grid-area: item2;
    justify-self: start;  /* Aligns to the left    */
    align-self: end;      /* Aligns to the bottom  */
}

#item3 {
    grid-area: item3;
    justify-self: center;  /* We know this already */
    align-self: center;    /* We know this already */
}

The result should look like this:

Easy!  All four of the properties that we just covered accept the same 4 potential values:

  • justify-items - start | end | center | stretch
  • justify-self
  • align-items
  • align-self

Once you understand these 4 properties and how they work, alignment becomes a breeze with the CSS grid.

Muscle memory is where it's at, so let's run through several other common use cases for alignment.

Align to the Bottom with the CSS Grid

It's common to have a footer on a layout, and it's also common to want that footer to stay at the bottom of the browser.

Let's scrap everything in our HTML and start fresh with the following marketup:

<body>
    <div class="content">
        <p>My content</p>
    </div>
    <footer>
        <p>This is my footer bar</p>
    </footer>
</body>

Next, remove everything from our current main.css except for the body,html {}  ruleset at the top, and add this:

body {
    margin: 0;

    display: grid;
    grid-template-rows: auto 50px;
    grid-template-areas:
        "content"
        "footer";
}

.content {
    grid-area: content; /* This is not necessary for this to work
                           but I'm naming it for future use */
    justify-self: center;
    align-self: center;
}
footer {
    grid-area: footer; /* This is not necessary for this to work
                          but I'm naming it for future use */

    background-color: lightgray;
    padding:10px;
}

The result should now look like this:

Ah, this is so easy. Let's try adding a sidebar to this:

Adding a Sidebar with the CSS Grid

We have a main content section and a footer, let's try adding a sidebar to the left of the UI.

Adjust the HTML like so:

<body>
    <aside>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Contact</a></li>
        </ul>
    </aside>
    <div class="content">
        <p>My content</p>
    </div>
    <footer>
        <p>This is my footer bar</p>
    </footer>
</body>

And in our CSS, we now have to create 2 columns, adjust our rows property and also the grid template areas property:

body {
    margin: 0;

    display: grid;
    grid-template-rows: auto 50px;
    grid-template-columns: 12% auto;
    grid-template-areas:
        "sidebar content"
        "footer footer";
}

aside {
    grid-area: sidebar;
    background-color: gray;
}

/* This stuff below didn't change at all */

.content {
    grid-area: content; /* This is not necessary for this to work
                           but I'm naming it for future use */
    justify-self: center;
    align-self: center;
}
footer {
    grid-area: footer; /* This is not necessary for this to work
                           but I'm naming it for future use */
    background-color: lightgray;
    padding:10px;
}

The result should look like this:

Conclusion

As you can see, it's extremely straight forward to align your grid items with the CSS Grid. Why wasn't it this easy from the beginning?


Share this post




Say something about this awesome post!