Aligning a Single Element Along the Horizontal Axis of a CSS Grid

Alignment along the horizontal axis can be set not only in the parent element, but also for each child element separately. The justify-self property is used for this purpose.

At the beginning of the horizontal axis

Let's set the alignment for our first element to the start of the horizontal axis:

html<div id="parent">
  <div id="elem1">1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
css#parent {
  display: grid;
  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;
}
#elem1 {
  justify-self: start;
}

Результат:

At the center of the horizontal axis

Let's set the alignment of the first element to the center of the horizontal axis:

html<div id="parent">
  <div id="elem1">1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
css#parent {
  display: grid;
  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;
}
#elem1 {
  justify-self: center;
}

Результат:

At the end of the horizontal axis

Let's set the alignment for the first element to the end of the horizontal axis:

html<div id="parent">
  <div id="elem1">1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
css#parent {
  display: grid;
  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;
}
#elem1 {
  justify-self: end;
}

Результат:

Practical tasks

Задание 1

Create a grid of five elements arranged in two rows. Align the second element to the origin of the horizontal axis.

Задание 2

Now arrange the grid elements into three rows and set the alignment of the third element to the center of the grid's horizontal axis.

Задание 3

Modify the previous problem so that the fifth element is aligned to the end of the horizontal axis.