3 short lines of CSS (excluding vendor prefixes) using transform: translateY will vertically center whatever we want, even if we don’t know the elements height.
The CSS property transform: translateY function allows us to achieve vertical center without having to use absolute positioning or setting line-heights, which require you to either know the height of the element or only works on single-line text etc.
The code you need is below:
.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}
and if you need full browser support, remember to add the below vendor prefixes:
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
As an aside, if you notice your element is being placed on a half pixel, add the following code to the parent element to preserve-3d.
.parent-element {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}