Aligning a Single Element Along the Vertical Axis of a CSS Grid
Similarly, you can align elements along the vertical axis using the align-self property. Let's look at examples of how this works.
At the beginning of the vertical axis
Let's set the alignment for the first element to the start of the vertical axis:
<div id="parent">
<div id="elem1">1</div>
<div id="elem2">2</div>
<div id="elem3">3</div>
<div id="elem4">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 {
align-self: start;
}
:
At the center of the vertical axis
Let's set the alignment of the first element to 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 {
align-self: center;
}
:
At the end of the vertical axis
Let's set the alignment for our first item in the grid to the end 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 {
align-self: end;
}
:
Practical tasks
Create a grid of five elements arranged in two columns. Align the third element to the start of the grid's vertical axis.
Now arrange the grid items across three columns and set the second item to be aligned to the center of the grid's vertical axis.
Modify the previous task so that the fourth and fifth elements are aligned to the end and beginning of the vertical axis, respectively.