Learn
Advanced CSS Grid
Justify Content

In the previous exercise, we learned how to position elements within their columns. In this exercise, we will learn how to position a grid within its parent element.

We can use justify-content to position the entire grid along the row axis.

It accepts these values:

  • start — aligns the grid to the left side of the grid container
  • end — aligns the grid to the right side of the grid container
  • center — centers the grid horizontally in the grid container
  • stretch — stretches the grid items to increase the size of the grid to expand horizontally across the container
  • space-around — includes an equal amount of space on each side of a grid element, resulting in double the amount of space between elements as there is before the first and after the last element
  • space-between — includes an equal amount of space between grid items and no space at either end
  • space-evenly — places an even amount of space between grid items and at either end

There are several other values that justify-content accepts, which you can read about on the Mozilla Developer Network. The definitions for these values can also be found in the documentation. It is important to note that the page with the definitions includes some values that are not accepted in CSS Grid layout.

<main> <div class="left">Left</div> <div class="right">Right</div> </main>
main { display: grid; width: 1000px; grid-template-columns: 300px 300px; grid-template-areas: "left right"; justify-content: center; }
  1. In the example above, the grid container is 1000 pixels wide, but we only specified two columns that are 300 pixels each. This will leave 400 pixels of unused space in the grid container.
  2. justify-content: center; positions the columns in the center of the grid, leaving 200 pixels on the right and 200 pixels on the left of the grid.

This property is declared on grid containers.

Instructions

1.

Expand the web browser to the right. You might notice that the two columns of recipe cards are off-center.

Add the justify-content property to the main rule set in style.css and set its value to space-between.

What happens to the columns?

2.

Change the value of the justify-content property in the main to space-around.

Expand the browser again. Now what happened to the columns?

3.

Change the value of the justify-content property in the main to end.

Expand the browser again to see the differences.

4.

Change the value of the justify-content property in the main to center.

Expand the browser again to see the differences. Now, all of the elements should be perfectly centered on the page!

Feel free to try any of the values that we didn’t practice.

Folder Icon

Take this course for free

Already have an account?