Subscribe On YouTube

Introduction

CSS Grid is the new layout system natively supported by browsers. In comparison to e.g. Bootstrap’s Grid system CSS Grid do not require to include any external libraries and is applied by adding CSS rules to parent elements (Grid Container) and to child elements (Grid Items).

CSS Grid is a two-dimensional grid layout system which works with columns and rows. In comparison to Flexboxes (which are mainly one-dimensional) the CSS Grid layout system enables you to build more complex layouts. However, it’s possible to combine both: Flexbox and Grid Layout in CSS.

In contrast to the Bootstrap Grid Layout system it’s much more cleaner to define the layout structure in CSS only. You do not need to include layout definition within your markup codes. This makes the markup code easier to read and you’re able to quickly adapt the layout if needed without needing to rearrange your markup code.

This tutorial will provide you with a general introduction to the CSS Grid layout system. As a prerequisite you should have a basic understanding of HTML and CSS.

Terminology

Before diving into the details of the CSS Grid layout system let’s define some important terms. In the following you can see on schematic overview of a CSS Grid:

Grid Container

The grid container is the parent element of a grid layout system. The CSS rule display: grid needs to be applied to this container in order to active the CSS Grid layout mode.

Grid Line

Grid lines are the lines which defines the structure of the grid and are dividing the grid into cells. Lines in a grid can be either vertically (dividing the grid in columns) or horizontally (dividing the grid into rows).

Each grid line has a unique number starting from 1 on the left side of the grid / on top of the grid. This line numbering is used to define grid area. You’ll see a practical example later on.

Grid Cell

A grid cell is the smallest unit inside a grid and is the area between two adjacent column grid lines and two adjacent row grid lines.

Grid Area

Inside a grid a grid area can be any area which is surrounded by four lines. Each area can comprise of any number of cells.

Grid Item

Any direct child elements of the parent grid container are called grid items.

Browser Support

Since the beginning of 2017 CSS Grid layout support has been shipped with the public released of all majors browsers like Firebox, Chrome, Opera and Safari.

The IE/Edge version of the specification is prefixed with an -ms prefix and the properties implemented in IE/Edge. This means that the default CSS property names like:

grid-template-columns

needs to be changes in IE/Edge to:

-ms-grid-columns

Creating a Grid Container

Preparation

Let’s start by creating a basic Grid Container first. To do so we need to start with a basic HTML structure like you can see in the following listing:

<!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 - Demo 01</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container"> </div> </body> </html>

The body section contains one <div> element to which the container class is assigned.

Display

In order to activate the Grid layout mode for the div section we need to apply the display property to the container class in the following way (in styles.css):

.container { display: grid; }

Defining Grid Column And Rows

grid-template-columns / grid-template-rows

The next step is to define grid columns and rows. This is done by adding CSS properties grid-template-columns and grid-template-rows to the definition of class container:

.container { display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows: 1fr 1fr 1fr; }

Here we’re defining a 3×3 grid by assigning three values separated by a free space to both grid-template-columns and grid-template-rows.

The value provided can be a length, a percentage, or a fraction (like in the example above) of the free space in the grid.

Let’s add some items to the grid to make the layout visible:

<div class="container"> <div class="item item1">Lorem ipsum dolor sit amet consectetur adipisicing elit. Itaque cupiditate aliquid optio, quia id voluptatem laudantium nisi? Vel, dicta blanditiis!</div> <div class="item item2">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Magnam voluptatum ducimus ipsam, odit non commodi illo nam iste placeat ex?</div> <div class="item item3">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Illo excepturi hic architecto eveniet alias tenetur debitis quam non natus vel.</div> <div class="item item4">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Id mollitia esse, recusandae velit maiores deserunt possimus. Nihil consectetur aspernatur a repellendus aut eum, saepe, cum similique error, sunt sequi blanditiis optio soluta laborum fugiat nesciunt pariatur sed facere impedit suscipit.</div> <div class="item item5">Lorem ipsum dolor sit amet consectetur adipisicing elit. Labore tenetur voluptates atque reprehenderit recusandae, quasi inventore aliquam est repellat! Id officiis eius voluptatibus, mollitia natus illum voluptatem error necessitatibus accusantium, doloribus quidem earum itaque velit laboriosam nulla in quia qui.</div> <div class="item item6">Lorem ipsum dolor sit, amet consectetur adipisicing elit. Hic quibusdam, impedit voluptate, quaerat veritatis ab odit dolore beatae et deserunt laboriosam dolorem saepe molestiae magni officia earum unde similique, ullam velit aliquam sapiente ipsum. Dolorum, veniam ea, qui delectus aspernatur maiores temporibus maxime placeat quae commodi deleniti dicta obcaecati, nihil libero. Minima id ipsum excepturi deserunt deleniti earum magnam numquam!</div> </div>

Furthermore add the following CSS code to styles.css to give each item a green background color:

.item { background: rgba(55, 143, 63, 0.603); }

The result should now look like the following:

We’ve added six grid items to our nine cell grid, so that only first and second row cells are filled. The third line is empty.

grid-column-gap / grid-row-gap

Having defined the number of rows and columns in our grid we can also add gaps between cells. This can be done by adding CSS properties grid-column-gap and grid-row-gap to the grid wrapper class:

.container { display: grid; grid-template-columns: 1fr 1fr 1fr; grid-template-rows: 1fr 1fr 1fr; grid-column-gap: 10px; grid-row-gap: 10px; }

It’s also possible to use the shorthand notation grid-gap in the following way:

grid-gap : <grid-row-gap> <grid-column-gap> ;

The result should now have changed to the following:

Aligning Content

Along The Row Axis With justify-items

By adding the CSS property justify-items to the grid container class you can align the content inside a grid item along the row axis. The following values can be assigned to justify-items:

start : aligns to the left

: aligns to the left end : aligns to the right

: aligns to the right center : aligns in the center

: aligns in the center stretch: stretches the content to fill the complete width (default)

Let’s try out to set justify-items to different values. First let’s change the content for the first grid items to contain only the text “Test”:

<div class="item item1">Test</div>

Next, lets add

justify-items: center;

to the container class. The output in the browser changes to the following:



Because the first grid item is not requiring the complete width you can see the effect of the center alignment.

Along The Column Axis With align-items

Aligning along the column axis is also possible by using the align-items CSS property. Again, the following values are available:

start : aligns to the top

: aligns to the top end : aligns to the bottom

: aligns to the bottom center : aligns in the center

: aligns in the center stretch: stretches the content to fill the complete height (default)

Lets apply the following to the definition of class container:

align-items: center;

The output should now change to the following:



All grid items are now centered vertically in their cell.

Aliging Single Item Content

You now know how to align grid content with CSS properties align-items and justify-items. It’s also possible to do the same on item level. Therefore we need to apply the CSS properties justify-self (aligns the content inside a grid item along the row axis) and align-self (aligns the content inside a grid item along the column axis).

We’ve already assigned individual CSS classes to our grid items (item1 – item6), so that it’s easy to apply the necessary styling to a align the content of single elements.

Let’s add the following CSS code to file styles.css to see the resulting effect:

.item1 { justify-self: end; align-self: end; }

The content of the first grid item has been moved into the lower right corner of the first grid cell.

Location of Grid Items

grid-column-start / grid-column-end / grid-row-start / grid-row-end

So far our example showed that the defined grid elements are put into the grid cells one by another. Each grid item is placed inside one grid cell. You can change the grid item’s location and define that a grid item should span across multiple grid cells by using CSS properties grid-column-start, grid-column-end, grid-row-start, and grid-row-end.

To specify the location with these properties we’re referring to specific grid lines. Remember the lines are automatically numbered starting by 1 (both in row and column direction).

Let’s say we’d like to let grid item 4 span across all cells in the second row:

.item4 { grid-column-start: 1; grid-column-end: 4; }

Here we’re defining that the space for grid item 4 (the div element with class assignment item4) should start at column line 4. This is the very left vertical line of the grid. To span across all cells in this row we’re setting grid-column-end to value 4. Line 4 is the line at the very right of the grid. The result should then look like the following:



There is also a shorthand notation, instead of writing

grid-column-start: 1; grid-column-end: 4;

you can also just write:

grid-column: 1/4;

Grid Template Areas / Grid Areas

Inside a grid a grid area can be any area which is surrounded by four lines. Each area can comprise of any number of cells. To describe a grid area we’ve already learned that CSS properties grid-column-start, grid-column-end, grid-row-start, and grid-column-end can be used.

However there is another possibility of defining grid areas. By applying the property grid-template-area you are able to describe the grid areas in the grid by assigning names to the cells. Later on those named areas can be used together with the CSS property grid-area which is applied on grid item level.

Let’s take a look at a practical example. Just imaging we want to define the following layout for our application:

Using our 3×3 grid again that would mean that the the cells belong to the four grid areas in the following way:

Here we have defined the following grid areas are defined:

Header

Sidebar

Content

Footer

Let’s see how we can define a grid of that structure easily. We start with creating a new HTML file which contains one top level div element in the body section of the page. Furthermore this div contains four child div elements which corresponds to the areas of the layout: Header, Sidebar, Content, and Footer.

<!DOCTYPE html> <html lang="en"> <head> <title>CSS Grid - Demo 02</title> <link rel="stylesheet" href="styles2.css"> </head> <body> <div class="container"> <div class="item1">Header</div> <div class="item2">Sidebar</div> <div class="item3">Content</div> <div class="item4">Footer</div> </div> </body> </html>

grid-template-areas / grid-area

Instead of using properties grid-column-start, grid-column-end, grid-row-start, and grid-column-end on item level we’re using the properties grid-template-areas on the level of the grid container in the following way:

.container { width: 100vw; height: 100vh; display: grid; grid-template-columns: 1fr 3fr 3fr; grid-template-rows: 1fr 10fr 1fr; grid-template-areas: "header header header" "sidebar content content" "footer footer footer"; }

The syntax which is used for the value which is assigned to grid-template-areas providers a visual representation of the grid layout. Repeating a name of an area multiple times (e.g. three times the area name header in the first row) causes this grid area to span across all three grid cells in the first row.

The grid area names which are used for defining the layout can then be used together with the property grid-area on grid item level, e.g..

.item1 { grid-area: header; }

This makes the item span across the defined header area (all three cells in row one).

The complete CSS code which is needed to get the layout in place can be seen in the following:

body { padding: 0px; margin: 0px; } .container { width: 100vw; height: 100vh; display: grid; grid-template-columns: 1fr 3fr 3fr; grid-template-rows: 1fr 10fr 1fr; grid-template-areas: "header header header" "sidebar content content" "footer footer footer"; } .item1 { grid-area: header; background: #86B6E9; } .item2 { grid-area: sidebar; background: #DDE986; } .item3 { grid-area: content; background: #B8E986; } .item4 { grid-area: footer; background: #E9C886; }

The result in the browser should now look like the following:

ONLINE COURSE: Ultimate CSS Grid Course Create CSS Grid layouts using the new grid system & use it together with CSS3 Flexbox and Sass for an amazing workflow The Ultimate CSS Grid Course: From Beginner to Advanced Know and understand the CSS Grid specification

Know in how far CSS Grid complements Flexbox

Use all new properties defined for CSS grid layouts

Create real-world grid layouts blazingly fast

Understand even advanced concepts from the CSS Grid spec Go To Course