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">
Content
</div>
.container {
display: block;
align-content: center;
height: 100%;
}
This feature is supported by all modern browsers:
Flexbox
<div class="container">
<div class="center-item">
Content
</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
</div>
</div>
.container {
display: grid;
place-items: center;
height: 100%;
}
This method uses the CSS grid layout to center the child element vertically and horizontally within the parent container. The place-items
property set to center
aligns the child element both vertically and horizontally.
Table Cell
<div class="container">
<div class="center-item">
Content
</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.
Transforms
<div class="container">
<div class="center-item">
Content
</div>
</div>
.container {
position: relative;
height: 100%;
}
.center-item {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
This method uses CSS transforms to center the child element vertically within the parent container. The top: 50%
property positions the child element vertically halfway down the parent container, and the transform: translateY(-50%)
property moves the child element upwards by half its own height, effectively centering it vertically within the parent container.
Leave a Reply