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:
<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;
}
:
At the center of the horizontal axis
Let's set the alignment of the first element to the center of the horizontal 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;
}
:
At the end of the horizontal axis
Let's set the alignment for the first element to the end of the horizontal 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;
}
:
Practical tasks
Create a grid of five elements arranged in two rows. Align the second element to the origin of the horizontal axis.
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.
Modify the previous problem so that the fifth element is aligned to the end of the horizontal axis.