November 06, 2016
Horizontal and Vertical Align Anything with CSS
Using translate()
is one of the easiest ways^[Flexbox also provides a great solution. See Solved by Flexbox: Vertical Centering] to instantly horizontal and vertical align any element with CSS without knowing its dimensions.
Vertical Align
You probably know the “vertical align with just 3 lines of CSS” trick, which uses translateY()
.
.my-element {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
Horizontal Align
But did you know it’s also possible to use translate()
to horizontal align elements?
.my-element {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
Vertical and Horizontal Align
Mixing both, we can horizontal and vertical align anything!
.my-element {
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
}
See JSBin.