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>
3
Answers
You can simply center divisions inside divisions via adding
attributes to main container. So this will work:
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;
andjustify-self: center;
properties can be used.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>
.<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.You can try it