
There are several ways to vertically center an object with CSS:
Flexbox
<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: 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 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.
Transforms
<div class="container"> <div class="center-item"> <!-- content goes here --> </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.
Foto von Jackson Sophat auf Unsplash.