Aligning Content Along the Horizontal Axis in CSS Grid

In a grid, you may need to not only position but also align the content along the horizontal axis of the grid. In this case, we use the justify-content property, which is set on the parent element. Let's look at examples of how this property works.

At the beginning of the axis

Let's set the alignment for our elements to the beginning of the horizontal axis:

html<div id="parent">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>
css#parent {
  display: grid;
  justify-content: start;
  grid-template-columns: 100px 100px;
  grid-template-rows: repeat(3, 1fr);
  grid-gap: 10px;
  padding: 10px;
  border: 2px solid #696989;
  height: 200px;
  width: 400px;
}
#parent > div {
  grid-gap: 10px;
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #696989;
}

Результат:

At the center of the axis

Now let's set the alignment for our elements to the center of the horizontal axis:

html<div id="parent">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>
css#parent {
  display: grid;
  justify-content: center;
  grid-template-columns: 100px 100px;
  grid-template-rows: repeat(3, 1fr);
  grid-gap: 10px;
  padding: 10px;
  border: 2px solid #696989;
  height: 200px;
  width: 400px;
}
#parent > div {
  grid-gap: 10px;
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #696989;
}

Результат:

At the end of the axis

Let's set the alignment for our elements to the end of the horizontal axis:

html<div id="parent">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>
css#parent {
  display: grid;
  justify-content: end;
  grid-template-columns: 100px 100px;
  grid-template-rows: repeat(3, 1fr);
  grid-gap: 10px;
  padding: 10px;
  border: 2px solid #696989;
  height: 200px;
  width: 400px;
}
#parent > div {
  grid-gap: 10px;
  padding: 10px;
  box-sizing: border-box;
  border: 1px solid #696989;
}

Результат:

Practical tasks

Задание 1

Create a grid of six elements arranged in two columns. Align the elements to the start of the horizontal axis of the grid.

Задание 2

Now arrange the grid items across three columns and set the alignment of the items to be centered on the horizontal axis of the grid.

Задание 3

Modify the previous task so that the elements are aligned at the end of the horizontal axis.