There are several ways to vertically center an object with CSS:
align-content
Property
Since Google I/O 2024, a new CSS solution to vertically align an object was shown by the Chrome Development Team. Inside a block element it’s now possible to use the align-content
property. The alignment works without additional html blocks or CSS definitions and excludes the side effects when using a workaround like Flex or Grid layout.
The align-content
property can now be applied directly to a block container:
<div class="container">
<div class="center-item">
<!-- content goes here -->
</div>
</div>
.container {
display: flex;
align-items: center;
height: 100%;
}
This method uses the CSS flexbox layout to center the child element vertically within the parent container. The align-items
property set to center
aligns the child element along the cross axis.
Grid Layout
<div class="container">
<div class="center-item">
<!-- content goes here -->
</div>
</div>
.container {
display: table-cell;
vertical-align: middle;
height: 100%;
}
This method uses the CSS table layout to center the child element vertically within the parent container. The display: table-cell
and vertical-align: middle
properties treat the parent container as a table cell and vertically center the child element within it.