Aligning a Single Element Along Both Axes of a CSS Grid
It is possible to align a single element along both the horizontal and vertical axes by combining the justify-self and align-self properties.
At the beginning of the horizontal and the center of the vertical
Let's set the alignment for our first element to the origin of the horizontal and vertical axes:
<div id="parent">
<div id="elem1">1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
#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;
align-self: center;
}
:
In the center of the horizontal and the beginning of the vertical
Now let's set the alignment of the first element to the center of the horizontal axis and the origin of the vertical axis:
<div id="parent">
<div id="elem1">1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
#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;
align-self: start;
}
:
At the end of the horizontal and the center of the vertical
Let's set the alignment of the first element to the end of the horizontal axis and the center of the vertical axis:
<div id="parent">
<div id="elem1">1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
#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;
align-self: center;
}
:
Practical tasks
Create a grid of six elements and arrange them in two rows. Align the second element to the start of the horizontal axis and the center of the vertical axis.
Now arrange the grid elements in three rows and align the third element to the center of the horizontal axis and the end of the vertical axis.
Modify the previous task so that the fourth element is aligned to the end of the horizontal axis and the center of the vertical axis.
Now make the fifth element align to the start of the horizontal axis and the start of the vertical axis, and the sixth element align to the end of the horizontal axis and the center of the vertical axis.