In this demo there are two divs within the css grid container div. Is it possible to center them so that the second item sits within and on top of the first item and both are centered vertically and horizontally? I thought perhaps align-self
would do it …
<div
style="
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr;
height: 200px;
width: 200px;
background-color: blue;
"
>
<div
style="
width: 100px;
height: 100px;
background-color: red;
align-self: center;
"
></div>
<div
style="
align-self: center;
width: 50px;
height: 50px;
background-color: yellow;
"
></div>
</div>
>Solution :
Yes, it is possible to centre the two elements within the CSS grid container so that the second item sits within and on top of the first item, and both are centred vertically and horizontally. The align-self: center;
and justify-self: center;
properties can be used.
<div
style="
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr;
height: 200px;
width: 200px;
background-color: blue;
position: relative; /* Added to create a positioning context */
"
>
<div
style="
width: 100px;
height: 100px;
background-color: red;
align-self: center;
justify-self: center;
position: relative; /* Added to create a positioning context */
"
></div>
<div
style="
align-self: center;
justify-self: center;
width: 50px;
height: 50px;
background-color: yellow;
position: absolute; /* Positioned absolutely within the parent */
top: 50%; /* Move 50% down from the top */
left: 50%; /* Move 50% from the left */
transform: translate(-50%, -50%); /* Center the item */
"
></div>
</div>
I’ve added the following changes:
justify-self: center;
has been added to both<div>
elements to centre them horizontally within the grid cell.position: relative;
has been added to both<div>
elements to create a positioning context for the absolute positioning of the inner<div>
.- For the inner yellow
<div>
,position: absolute;
is used to position it absolutely within the parent container. top: 50%; and left: 50%;
are used to position the yellow<div>
50% down from the top and 50% from the left, which places its top left corner at the centre of the parent.transform: translate(-50%, -50%);
is used to shift the yellow<div>
half of its width and height to centre it perfectly within the parent.
With these adjustments, the two <div>
elements will be centred both vertically and horizontally, and the second item will sit within and on top of the first item.